4

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?

3
  • What is the (?! ) for? Commented Dec 1, 2011 at 8:50
  • 2
    @Jergason negative lookahead: regular-expressions.info/lookaround.html Commented Dec 1, 2011 at 8:52
  • 1
    I'm not sure what you mean; /^(?! )[a-zA-Z]*[a-zA-Z ]*$/.test("") === true. Commented Dec 1, 2011 at 8:54

2 Answers 2

14

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/

Sign up to request clarification or add additional context in comments.

1 Comment

@OrangeTux You're welcome :) Don't forget to mark it as an accepted answer by clicking on the check box outline to the left of this answer
0

Could also use this:

if (subject.match(/^(?=[a-z ]*$)(?=\S)(?=.*\S$)/i)) {
    // Successful match
}

Using only lookaheads. Although I would go with @Marcus answer.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.