2

How would you go about validating 2 different regular expressions in jQuery or JS?

My JS Code:

function validate(){
    var MyField = document.getElementById('MyField');
    if (MyField.value == null || !MyField.value.toString().match(/^(\d{3})-?\d{2}-?\d{4}$/) || !MyField.value.toString().match(/^(\d{2})-?\d{7}$/));
    alert('Ivalid Entry ...'); 
    return false;
}

My HTML:

<form action="">
  <input id="MyFIeld" name="MyField" type="text" />
  <input type="submit" value="Submit" onClick="validate();" />
</form>

Basically its for Tax ID and SSN formatting properly. ##-####### or ###-##-#### ... I am open to JS or jQuery solutions...all help much appreciated.

3
  • if you have hard time on that, you can use this, digitalbush.com/projects/masked-input-plugin Commented Jul 3, 2010 at 4:15
  • I'd suggest just filtering everything but valid characters (eg. numbers). This way it doesn't matter if the user uses dashes, spaces or whatever as separators. You can just then compare if the field has enough numbers or whatever characters required. Commented Jul 3, 2010 at 4:21
  • 1
    and whatever you validate on client side, don't forget to validate also on server side... Commented Jul 3, 2010 at 4:24

1 Answer 1

4

What I normally do in cases like that is have a "library" of regex tests:

var regexTest = function() {
   this.TaxId = /^(\d{2})-?\d{7}$/;
   this.SSN = /^(\d{3})-?\d{2}-?\d{4}$/;
}

This separates your regex in case it needs to be changed for some reason. Trust me, it will happen from time to time. (Maybe not SSN/TaxId, but it's good practice)

Then I setup an event block similar to what you have (jQuery makes it easy) to provide instant feedback:

$("#MyField").bind("blur keyup",
   function() {
      var myVal = $(this).val(); // should store $(this) in a var instead
      if(regexTest.SSN.test(myVal) || regexTest.TaxId.test(myVal)) {
         $(this).css("background-color", "");
      } else {
         $(this).css("background-color", "#FF0000");
      }
   }
);

I know this doesn't validate on submit, but it provides feedback to the user as they type. (It's not real bad on overhead either as long as you keep your validation simple.) Then perform validation of your data server side (people can bypass validation checks) and you should be good. Yes, it's not validating the data before submit, but if the user sees a red box, they know it's bad data.

There are, of course, validation libraries out there as noted in some comments, but I like to write my own sometimes. ;)

Sign up to request clarification or add additional context in comments.

1 Comment

Also bind to the form and validate when it is submitted.

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.