views:

30

answers:

1

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.

+2  A: 

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. ;)

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