2

I'd like to evaluate a form field using a regex.

What expression do I use to actually compare the value to the regex?

I'm imagining something thus:

if($('#someID').val() == /someregex/) {doSomething()}

But that doesn't work. Any advice?

6 Answers 6

3

Use

if (/^someregex$/.test($('someID').value()) {
     // match
} else {
     // no match
}
Sign up to request clarification or add additional context in comments.

Comments

0

Note that there is no value() method in jQuery, you need to use val() and match like this:

if($('#someID').val().match(/someregex/) {
  // success
}

More Info:

Comments

0

use the match method of the strings..

string.match(regexp)

so in your case

if( $('#someID').value().match(/someregex/) ) {doSomething()}

Comments

0

I think you're looking for .test():

var myRegex = /someregex/;
if ( myRegex.test($('#someID').value()) ) {
    doSomething();
}

You can use exec() to check it and get an array of it's matches, or match() from the string object.

Comments

0

We don't compare values to regular expressions. We use regular expressions to test if a value matches a pattern.

Comments

0

Something like:

if (/myRegExp/.test($('#myID').val()) { 
  //... do whatever 
}

see http://www.evolt.org/regexp_in_javascript

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.