I have a text field with the following validation rules:
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
Views
Replies
Total Likes
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?
Views
Replies
Total Likes
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
Views
Replies
Total Likes
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
Views
Replies
Total Likes
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);
}
Views
Replies
Total Likes
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
Views
Replies
Total Likes
Views
Likes
Replies
Views
Likes
Replies
Views
Likes
Replies