Reputation: 1472
I have a check on submit to validate some fields and I need to check for only numbers and dashes:
var numPattern = /^[0-9\-]+$/;
//UI field null check
if (ssn != (numPattern.test(ssn))) {
displayError(Messages.ERR_TOPLEVEL);
}
if (accntNoCL != (numPattern.test(accntNoCL))) {
displayError(Messages.ERR_TOPLEVEL);
}
This is not working for some reason. Any ideas why that is?
Upvotes: 1
Views: 2385
Reputation: 465
test
is a predicate, it returns a boolean:
var numPattern = /^[0-9\-]+$/;
numPattern.test("hello, world!"); // false
numPattern.test("123abc"); // false
numPattern.test("123"); // true
numPattern.test("12-3"); // true
Upvotes: 2
Reputation: 38436
The regex.test()
function, or numPattern.test()
in your case, returns a boolean true
/false
result.
In your code, if (ssn != numPattern.test(ssn))
, you're checking if the result is equal to the value you're testing.
Try changing it to the following:
if (!numPattern.test(ssn)) {
Upvotes: 4
Reputation: 44259
test
returns a boolean, not a match. Simply use
if (!numPattern.test(ssn)) {
displayError(Messages.ERR_TOPLEVEL);
}
if (!numPattern.test(accntNoCL)) {
displayError(Messages.ERR_TOPLEVEL);
}
If you ever need a match, use either the match
function of strings or the exec
function of regex objects.
Upvotes: 1