I used preg_match for my server-side validation but I want to have a client side too.
For my PHP I allow those characters:
'/^[A-Za-z][a-zA-Z0-9 .:-,!?]+$/'
How would I make a white list of characters with match() in JavaScript?
EDIT:
I tried this but it didn’t work for some reason:
My debugger says, right before the if statement:
218SyntaxError: Invalid regular expression: range out of order in character class
$('#title').blur(function(){
input = $('#title').val();
var invalidChars = /^[^a-z][^a-z\d .:-,!?]+$/i;
if (!invalidChars.test(input)){
alert('true');
}
else {
alert('false');
}
});
Using
regex.test(str)is slightly more performant thanstr.match(regex)if all you want is to know if a match exists or not.Alternatively, you can early out if you see any invalid character:
This allows the regex test to stop the moment it sees a disallowed character.