I've a regular expression that allows a string to be empty. If it isn't empty the string may contain only letters and spaces. But it may not start or end with a space.
This RegExp should do this job:
^(?! )[a-zA-Z]*[a-zA-Z ]*$
I've tested it here: http://tools.netshiftmedia.com/regexlibrary/
But when I'm implementing this in my js, it doesn't allow a string to be empty.
This is the code
function validatePreposition(name) {
string = string = document.forms['form'][name].value;
pattern = new RegExp('^(?! )[a-zA-Z]*[a-zA-Z ]*$');
checkString(name, pattern, string);
}
function checkString(name, pattern, string) {
if(!pattern.test(string)) {
error[name] = 1;
} else {
error[name] = 0;
}
printErrors();
}
How change my code so that an empty string is allowed?
Try using this instead:
pattern = /(^[a-zA-Z]+(\s*[a-zA-Z]+)*$)|(^$)/;
It will either test for an empty string or test for a string that starts with a a-Z and may have unlimited amount of spaces in the string but have to end with a-Z.
You can see it in action here: http://jsfiddle.net/BAXya/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With