I have a regex that allows an empty string. If it is not empty, the string can only contain letters and spaces. But it cannot begin or end with a space.
This RegExp should do the job: ^(?! )[a-zA-Z]*[a-zA-Z ]*$
I tested it here: http://tools.netshiftmedia.com/regexlibrary/
But when I implement this in my js, it does not allow the 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 to change my code so that an empty string is allowed?
source share