Reputation: 319
I've been learning how Regular expressions work, which is very tricky for me. I would like to validate this chars below from input field. Basically if string contains any of these characters, alert('bad chars')
I found this code, but when I change it around doesn't seem to work. How can I alter this code to meet my needs?
var str = $(this).val();
if(/^[a-zA-Z0-9- ]*$/.test(str) == false) {
alert('bad');
return false;
} else {
alert('good');
}
Upvotes: 1
Views: 114
Reputation: 4234
You could just try the following:
if("/[\\/#&]/".test(str) == true) {
alert('bad');
return false;
} else {
alert('good');
}
NOTE: I'm not 100% on what characters need to be escaped in JavaScript vs. .NET regular expressions, but basically, I'm saying if your string contains any of the characters \
, /
, #
or &
, then alert 'bad'.
Upvotes: 1
Reputation: 39532
/^[a-zA-Z0-9- ]*$/
means the following:
^
the string MUST start here[a-zA-Z0-9- ]
a letter between a
and z
upper or lower case, a number between 0
and 9
, dashes (-
) and spaces.*
repeated 0 or more times$
the string must end here.In the case of "any character but" you can use ^
like so: /^[^\/\\#&]*$/
. If this matches true, then it doesn't have any of those characters. ^
right after a [
means match anything that isn't the following.
.
Upvotes: 1