We help IT Professionals succeed at work.

Avoid users save required field with spaces only.

Hi Experts,

I have the following code to avoid users entering "N/A" on a required field.

Now would like to add restriction of saving just space characters.

Thanks

$(":input[required]:visible").on("change", function() {
    var id = $(this).attr("id");
    var isName = id.indexOf("Last_Name")>0 || id.indexOf("First_Name")>0;
    var rgx =  isName ? /.*?N.*\/.*A/gi : /.*?N.*?A/gi;
    if($(this).val().length<6 && rgx.test($(this).val()) ) {
        $(this).val("");
        alert("N/A is not a valid input");
        var that = $(this);
        setTimeout(function(){
            that.focus();
        },350);
    }
});

Open in new window

Comment
Watch Question

Dr. KlahnPrincipal Software Engineer

Commented:
Match on the regex ^\s+$  --  "match a field containing only one or more whitespace characters."

Alternatively, use the regex ^\s*$ -- "match a field containing nothing, or only one more whitespace characters."

Side note:  An alternate regex for the "N/A" case which matches more possibilities would be:  \s*[nN]\s*/\s*[aA] which matches all of

n/a
N/A
n/A
   N/A
n  /A
N    / a


and more similar expressions.
Ryan ChongSoftware Team Lead

Commented:

try use the trim function, like:


if($(this).val().trim().length<6 && rgx.test($(this).val().trim()) ) {


Hi,

@Ryan,

Tried like this, does not seem to work.

$(":input[required]:visible").on("change", function() {
    var id = $(this).attr("id");
    var isName = id.indexOf("Last_Name")>0 || id.indexOf("First_Name")>0;
    var rgx =  isName ? /.*?N.*\/.*A/gi : /.*?N.*?A/gi;
    //if($(this).val().length<6 && rgx.test($(this).val()) ) {
    
if($(this).val().trim().length<6 && rgx.test($(this).val().trim()) ) {
        $(this).val("");
        alert("N/A is not a valid input");
        var that = $(this);
        setTimeout(function(){
            that.focus();
        },350);
    }
});

Open in new window


@Dr. Klahn,

Can you post the code along with the rest of the line so I can just copy/paste (sorry not so familiar with regex..).

Thanks,
Ben
Ryan ChongSoftware Team Lead

Commented:

The trim() function should worked well but I'm not sure for the rgx.test part

@Rayn,

The way i tested was just entering a space w/o any other character and it didn't prompt me to fill before submitting.

Thanks,
Ben
Ryan ChongSoftware Team Lead

Commented:

can you provide the valid as well as the invalid inputs?

Any value is valid except for "N/A,N.A.,N A,NA etc...", and just space w/o any letter/digit.

Thanks,
Ben
Ryan ChongSoftware Team Lead

Commented:

try this instead:


<script type="text/javascript">
            $(":input[required]:visible").on("change", function () {
                var id = $(this).attr("id");
                var isName = id.indexOf("Last_Name") > 0 || id.indexOf("First_Name") > 0;
                var rgx = isName ? /.*?N.*\/.*A/gi : /.*?N.*?A/gi;
                //if($(this).val().length<6 && rgx.test($(this).val()) ) {

                $(this).val($(this).val().trim());

                if (($(this).val().trim().length == 0) || (($(this).val().trim().length < 6)) && (rgx.test($(this).val().trim()))) {
                    $(this).val("");
                    alert("N/A is not a valid input");
                    var that = $(this);
                    setTimeout(function () {
                        that.focus();
                    }, 350);
                }
            });
        </script>

Hi Rayn,

You left out the code-:)

Thanks,
Ben
Ryan ChongSoftware Team Lead

Commented:

I think the editor got some problem, and I have reposted the codes in plain text.


see if you can review and test it?

Nope, it didn't work, was able to submit record with just single space.

Thanks,
Ben
Software Team Lead
Commented:

was able to submit record with just single space.

it worked for me. did you clear the cache?


>> if (($(this).val().trim().length == 0) || (($(this).val().trim().length < 6)) && (rgx.test($(this).val().trim()))) {

Thank you Ryan!
Now that I see the cache was the problem, maybe the 1st version does work...?

Thanks,
Ben
Ryan ChongSoftware Team Lead

Commented:

yup, this one should work:


<script type="text/javascript">
            $(":input[required]:visible").on("change", function () {
                var id = $(this).attr("id");
                var isName = id.indexOf("Last_Name") > 0 || id.indexOf("First_Name") > 0;
                var rgx = isName ? /.*?N.*\/.*A/gi : /.*?N.*?A/gi;
                //if($(this).val().length<6 && rgx.test($(this).val()) ) {

                $(this).val($(this).val().trim());

                if (($(this).val().trim().length == 0) || (($(this).val().trim().length < 6)) && (rgx.test($(this).val().trim()))) {
                    $(this).val("");
                    alert("N/A is not a valid input");
                    var that = $(this);
                    setTimeout(function () {
                        that.focus();
                    }, 350);
                }
            });
        </script>

Michel PlungjanIT Expert
Top Expert 2009

Commented:

DRY - Don't repeat yourself - also if the IDs START with Last_Name and First_Name then your test needs to be === or === 0



 $(":input[required]:visible").on("change", function() {    
    // const id = this.id;
    // const  isName = id.indexOf("Last_Name") === 0 || id.indexOf("First_Name") === 0; // not used?
    const val = $.trim(this.value);
    const re = /^n\/a$/i;
    if (val.length<6 || re.test(val)) { 
      alert("Please enter minimum 6 characters bearing in mind N/A is not a valid input"); 
      const $that = $(this);
      setTimeout(function(){ $that.focus(); },350);
    }
});  
@Michel,

Sorry for late response, currently my test server is down, hope to get it fixed by tom.

 // const id = this.id;
    // const  isName = id.indexOf("Last_Name") === 0 || id.indexOf("First_Name") === 0; // not used?
Why are you commenting out those lines?
I need to exclude those fields from testing for NA character as some names do have them.

However would appreciate if you can modify the code to accomplish the following.

1- Last and First name should only check for spaces, not for NA.
2- The current message to the user should only be used for NA, for spaces it should not require any msg.
3- Change the refex syntax as suggested above by Dr Klahn to include more scenarios.

Thanks,
Ben
Michel PlungjanIT Expert
Top Expert 2009

Commented:

Hi


It's bedtime here. I will look in 10 hours or so

Michel PlungjanIT Expert
Top Expert 2009

Commented:

First change


/^n\s*\/\s*a$/gi


Hi Michael,

It's bedtime here. I will look in 10 hours or so
-:)

First change

You mean?

const re = /^n\/a$/i;

Open in new window


for
const re = /^n\s*\/\s*a$/gi

Open in new window


Thanks,
Ben
Michel PlungjanIT Expert
Top Expert 2009

Commented:

Have a look at this


const testInput = function() {
  const id = this.id;
  const isName = id.indexOf("Last_Name") === 0 || id.indexOf("First_Name") === 0; // startsWith can be used too
  const val = $.trim(this.value); // if only spaces this is now empty
  const re = /^n\s*\/\s*a$/i; // handles n/a, N/A, n  /  a etc
  const error = [];
  this.setCustomValidity(""); // reset any error
  if (isName) {
    if (val != "" && val.length < 6) {
      this.setCustomValidity("Invalid field.")
      error.push("Please enter minimum 6 characters in your name fields");
    }
    // else this.removeAttribute("required"); // ??? Allow empty on required fields anyway?
  } 
  else if (re.test(val)) {
    const err = "N/A is not a valid input"
    this.setCustomValidity(err)
    error.push(err);
  }
  if (error.length > 0) {
    alert(error.join("\n"))
    const $that = $(this);
    setTimeout(function() {
      $that.focus();
    }, 350);
  }
}

$(":input[required]:visible").on("change", testInput);
It does allow to enter/save single space (on that site).

Thanks,
Ben
Michel PlungjanIT Expert
Top Expert 2009

Commented:

Here I have tested for empty after trimming


const testInput = function() { 
  const id = this.id; 
  const isName = id.indexOf("Last_Name") === 0 || id.indexOf("First_Name") === 0; // startsWith can be used too 
  const val = $.trim(this.value); // if only spaces this is now empty 
  const re = /^n\s*\/\s*a$/i; // handles n/a, N/A, n  /  a etc 
  const error = []; 
  this.setCustomValidity(""); // reset any error 
  if (isName) { 
    if (val === "" || (val != "" && val.length < 6)) { // do not allow space only
      this.value = val; // update with trimmed value 
      this.setCustomValidity("Invalid field.") 
      error.push("Please enter minimum 6 characters in your name fields"); 
    } 
  }  
  else if (re.test(val)) { 
    const err = "N/A is not a valid input" 
    this.setCustomValidity(err) 
    error.push(err); 
  } 
  if (error.length > 0) { 
    alert(error.join("\n")) 
    const $that = $(this); 
    setTimeout(function() { 
      $that.focus(); 
    }, 350); 
  } 
} 
 
$(":input[required]:visible").on("change", testInput); 




Hi Michel,

That seems to take care of the spaces as well.

Now whats about the message, how can it be modified to give appropriate message (in case of spaces should either give "no spaces allowed" or no message at all).

Thanks,
Ben
Michel PlungjanIT Expert
Top Expert 2009

Commented:

Replace the tests with this - fiddle:   https://jsfiddle.net/mplungjan/Lzv3rug6/

Note it is tricky to have required fields and to not require them. If you want to allow empty names, then we will need to remove the required from the fields and use a different selector


Here I just amended the texts to differentiate between empty and <6


  if (isName) {
    if (val === "" && val !== this.value) { // do not allow space only
      this.value = val; // update with trimmed value 
      error.push("Please do not use spaces only");
      this.setCustomValidity(error[error.length-1]);
    }
    else if (val.length < 6) { 
      error.push("Please enter minimum 6 characters in your name fields");
      this.setCustomValidity(error[error.length-1]);
    }
  }
  else if (re.test(val)) {  
    error.push("N/A is not a valid input");  
    this.setCustomValidity(error[error.length-1]); 
  }   
Hi,

Note it is tricky to have required fields and to not require them. If you want to allow empty names...
No, what I need is the following.

1- No empty spaces (only) whatsoever.
2- N/A should only be allowed by name fields.
3- System should give appropriate message, if empty should say empty, if NA should say NA not allowed.

Thanks,
Ben
Michel PlungjanIT Expert
Top Expert 2009

Commented:

So my code does what you need now?

Hi,

On email field it allows single space.

Thanks,
Ben
Michel PlungjanIT Expert
Top Expert 2009
Commented:

Once more then


const testInput = function() { 
  const id = this.id; 
  const isName = id.indexOf("Last_Name") === 0 || id.indexOf("First_Name") === 0; // startsWith can be used too 
  const val = $.trim(this.value); // if only spaces this is now empty 
  const re = /^n\s*\/\s*a$/i; // handles n/a, N/A, n  /  a etc 
  const error = []; 
  this.setCustomValidity(""); // reset any error 
  // no field is allowed a blank
  if (val === "" && val !== this.value) { // do not allow space only 
    this.value = val; // update with trimmed value  
    error.push("Please do not use spaces only"); 
    this.setCustomValidity(error[error.length - 1]); 
  } 
  if (isName) { // name fields must have more than 6 chars
    if (val.length < 6) { 
      error.push("Please enter minimum 6 characters in your name fields"); 
      this.setCustomValidity(error[error.length - 1]); 
    } 
  }  
  else if (re.test(val)) { // N/A or variations not allowed in other fields
    error.push("N/A is not a valid input"); 
    this.setCustomValidity(error[error.length - 1]) 
  } 
  if (error.length > 0) { 
    alert(error.join("\n")) 
    const $that = $(this); 
    setTimeout(function() { 
      $that.focus(); 
    }, 350); 
  } 
} 
 
$(":input[required]:visible").on("change", testInput); 
Thanks Michel, this time it worked.

I have another issue with that approach, will post another Q and send you a link.

Thanks,
Ben
Michel PlungjanIT Expert
Top Expert 2009

Commented:

Sure. Great you could use it