Expand my Community achievements bar.

Guidelines for the Responsible Use of Generative AI in the Experience Cloud Community.

How to check the space(s) in a text field?

Avatar

Former Community Member

I have a text field with the following validation rules:

  1. not null or empty;
  2. alphanumeric;
  3. 8 characters
  4. no space between or before/after

I wrote some Javascript functions to do the rules 1,2,3, but don't know how to do with 4:

1. check if null or empty

function isEmpty(str) {
if(str == null || str.length == 0) {
  return true;
}
return false;
}

2. check if alphanumeric

function validateAlphaNumeric( strVal ) {
var regExp  = /^[a-zA-Z0-9 ]*$/;
return regExp.test(strVal);
}

3. check if 8 characters

function validateInputLength( str, length ) {

if(str.length == length ){

  return true;

}

return false;

}

Is there a way that I update check 2 with a regular expression including check 4 (check if any space bar input)? Or shall I use a for loop to check the whole string, if so, how? Or any other solutions? Sorry, I am not very good in Javascripts and regular expressions.

Thanks

Sam

5 Replies

Avatar

Former Community Member

I tried the following to do the task:

function isSpaceChar( txt) {

for (var i=0;i<txt.length;i++) {
  var character=txt[i];
  if (character==" "){
   return true;
  }
}
return false;

}

Is there any better way than this?

Avatar

Level 10

Hi,

I think you should be able to change check 2 to include the 8 character check.

function validateAlphaNumeric( strVal ) {

    var regExp = /^[A-Z0-9]{8}$/i;

    return regExp.test(strVal);

}

Also the "/i" part means your regex is case insensitive so doesn't need the "a-z" part.  

There's more on regex's here https://developer.mozilla.org/en/docs/Web/JavaScript/Guide/Regular_Expressions.

Bruce

Avatar

Former Community Member

Hi Bruce,

Thanks for the reply. This is better than having a separate function to check the size of the string.

Any suggestion to check the space for requirement 4?

Appreciations also go to the recommended Regular Expression site. You are the man!

Thanks

Sam

Avatar

Level 10

Hi,

to check for spaces in the string you need to change the regular expression only a bit.

function validateAlphaNumeric( strVal ) {

    var regExp = /^[\SA-Z0-9]{8}$/i;

    return regExp.test(strVal);

}

Avatar

Former Community Member

Hi Radzmar,

Great! This is the regular expression I am looking for. So now I can have my three validation rules in one: e.g. alphanumeric, 8 characters, and the space checks, except null check.

Thanks

Sam