0

Trying to get the correct regex for this - only letters, spaces, hypens, and commas. So far this only works if you only input 1 charactor. Any more then that, and it returns false. Anyone able to help?

$('#submit').click(function () {
    var locationtest = /[^a-zA-Z \-\.\,]/;
    if (!locationtest.test($('#location').val())) {
        alert('Nope, try again!');
        $('#location').val('')
        return false;
    } else {
        alert('You got it!');
    }

});`
1
  • Your expression is correct. See the answer. Commented Mar 10, 2012 at 2:58

4 Answers 4

1

This should do it, it matches 1 or more characters within the set you described

/^[a-zA-Z \-\,]+$/

I took out the \., your description says letters, spaces, hyphens, commas

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

1 Comment

Oops, copied & pasted the \. from a PHP preg_match
0

You're close, you just need to specify how many times you want the character to appear.

The following code would specify 0 or more times var locationtest = /[^a-zA-Z -.\,]*/;

And this code would specify 1 or more times var locationtest = /[^a-zA-Z -.\,]+/;

The importance being the * and + characters.

Comments

0

Add a quantifier + and the global flag /g:

var locationtest = /[^a-zA-Z \-\.\,]+/g;

Comments

0

Your expression is correct, you just need to invert the match result.

/[^a-zA-Z \-\.\,]/

Will match if the string contains any char that is not what you want (the leading ^ in the character class).

I.e remove the !:

var locationtest = /[^a-zA-Z \-\.\,]/;
if (locationtest.test($('#location').val())) {
    alert('Nope, try again!');
    $('#location').val('')
    return false;
} else {
    alert('You got it!');
}

Note that empty string will pass as valid, if you don't want that, you can use this instead:

/[^a-zA-Z \-\.\,]|^$/

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.