isaac weathers
isaac weathers

Reputation: 1472

Checking for numbers and dashes

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

Answers (3)

Domenico De Felice
Domenico De Felice

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

newfurniturey
newfurniturey

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

Martin Ender
Martin Ender

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

Related Questions