0

I want to validate text-boxes in JQuery bit I want to use regex for this. As i am new to JQuery, can someone suggest me how regex can be used in JQuery to validate text string (where for e.g. regex is something like ^(?:[\\w\\s-])++$)?

5
  • why don't you use a JQuery validation plugin may i ask? Commented Apr 11, 2012 at 11:13
  • what characters want you to allow? An empty string should be valid? Please be more specific Commented Apr 11, 2012 at 11:14
  • RegExp does have nothing to do with jQuery. Test the string returned by .val() with Javascript RegExp functions. A real good online tester with cheatsheet is regex.larsolavtorvik.com Commented Apr 11, 2012 at 11:22
  • i am looking through validation plugin but not sure how i can validate using regex.. I have my regex with me, just want to know how to use it in jquery. Thanks @kontur Commented Apr 11, 2012 at 11:26
  • Missunderstood you then - so you want recommendations for jQuery plugins that allow you to hand them a regexp by which to validate? Commented Apr 11, 2012 at 11:31

3 Answers 3

2

Javascript regex functionality does not require JQuery, it can be used whether you have JQuery loaded or not.

Here are two great resources for javascript regex:

http://www.regular-expressions.info/javascript.html

http://www.w3schools.com/jsref/jsref_obj_regexp.asp

To fit this into JQuery:

if (/your regex/.test($("#textbox").val()))
{
    // Valid
}
else
{
    // Invalid
}
Sign up to request clarification or add additional context in comments.

Comments

1

http://www.jquery4u.com/syntax/jquery-basic-regex-selector-examples/

1 Comment

While this may theoretically answer the question, it would be preferable to include the essential parts of the answer here, and provide the link for reference.
0

Regular expressions aren't part of the jQuery framework, they're just part of javascript. To make them, either call the RegExp constructor, and pass your pattern as a string, or use the shorthand notation:

var newExp = new RegExp('^[0-9]{3,5}$');
//is the same as
var newExp = /^[0-9]{3,5}$/;

There is no need to escape backslashes twice in your example if you meant \w or \s. You might think about reading some tuts on regex, though as your pattern is, erm, flawed...

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.