Hello! I need to catch if someone just tries to enter a space in a required field, and still give them "field is required " alert. I can’t get the script to work, instead of replacing only spaces, it replaces the entire string:
fld = document.getElementById('DM');
var re =/\\s/g;
RegExp.multiline = true; // IE support
fld = (fld.value).replace(re,"");
This function checks for letters and spaces in a string. It also returns false if the string contains only spaces.
function isLettersAndSpaces(inpStr) {
//test if inpStr is 0 length
if(inpStr.length == 0) return false; //assume string is mandatory
var foundNonSpace = false;
//test if inpStr contains only letters or spaces
var validChars = /[a-z A-Z]/;
for(var i=0; i < inpStr.length; i=i+1) {
if(inpStr.charAt(i) != " ") foundNonSpace = true;
if(!validChars.test(inpStr.charAt(i))) {
return false;
}
}
//at this point all characters have been checked
return (foundNonSpace)? true : false;
}
If the function returns false you can give them your "field is required " or appropriate error message alert.
Actually, I made my original code work. So here it is:
function trim (str) {
var str2 = str;
str2 = str2.value.replace(/^\\s+/, '');
for (var i = str2.length - 1; i >= 0; i--) {
if (/\\S/.test(str2.charAt(i))) {
str = str2.substring(0, i + 1);
break;
}
}
return str2;
}