user3835480
user3835480

Reputation:

validating regex input fields

I get an alert telling me the address needs to contain only alpha numeric chars..

What i have for the regex is /^\w+$/

so when i put 123 Lane Street

it gives me that error. Any ideas why it's doing this?

 if (address == ""){
                  errors += "please enter a address \n";
                } else { 
                    addressRE = /^\w+$/;
                    if (address.match(addressRE)){
                      //console.log("address match");
                      //do nothing.
                    } else {
                      //console.log("address not a match");
                      errors += "Address should only contain alphanumeric characters \n";
                    } // end if
                }

Upvotes: 1

Views: 55

Answers (1)

zx81
zx81

Reputation: 41838

The space character in 123 Lane is not considered to be alphanumeric.

You need /^[a-z0-9 ]+$/i

The i turns on case-insensitive matching.

In JS:

if (/^[a-z0-9 ]+$/i.test(yourString)) {
    // It matches!
} else {
    // Nah, no match...
}

Upvotes: 2

Related Questions