Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript regular expression should allows empty and non-empty string, but it doesn't

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?

like image 651
OrangeTux Avatar asked Dec 09 '22 04:12

OrangeTux


1 Answers

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/

like image 137
Marcus Avatar answered Jan 19 '23 00:01

Marcus