Reputation: 83
Been trying now for a bit but can't figure this one out, I need a regular expression in Javascript that will match any term that only contains any of the following characters:
The digits 0-9, the minus sign (-), divide (/), multiply (*), plus (+), space ( ), left and right brackets ( ( and ) ), dot (.) and then lastly a comma (,).
If it contains anything else I want it to return false. It can contain multiples of each or only some of the characters in this set. What I have so far:
var regExResult = someString.test(/([^A-Z][^a-z][0-9]|[-]|[\+]|[*]|[,]|[.]|[)]|[(]|[\/]|[ ])+/g);
But for some reason it returns true even if the string contains only one character of these mentioned?
Any help would be greatly appreciated Thanks
Upvotes: 0
Views: 1483
Reputation: 7721
Here is an example code
var str = '1234-/*()., '; // results in 'good' alert
var str = '12a34-/*()., '; // results in 'bad' alert
if (/[^0-9-/*()., ]/.test(str)) { // true if it finds anything that is not allowed
alert('bad');
}
else { // if it didn't finds anything that is not allowed
alert('good');
}
Good luck :)
Upvotes: 0
Reputation: 32189
You can do that check as:
^[0-9*+ ().,-]+$
Demo: http://regex101.com/r/yK2cG5
Upvotes: 1