Go3Team
Go3Team

Reputation: 145

Jquery / Javascript Regex

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!');
    }

});`

Upvotes: 0

Views: 81

Answers (4)

Qtax
Qtax

Reputation: 33928

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 \-\.\,]|^$/

Upvotes: 0

pete
pete

Reputation: 25091

Add a quantifier + and the global flag /g:

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

Upvotes: 0

Evan
Evan

Reputation: 6143

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.

Upvotes: 0

yas
yas

Reputation: 3620

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

Upvotes: 1

Related Questions