1

I'm trying create a generic regex validator to use in a multi-input form which needs different rules for the individual input fields (also depending on other options selected).

I had this more or less working with vanilla JavaScript, but read that it would be simpler with jQuery. I found this code on another site, but I just can't get it to work.

Could someone please either point out what might be wrong with the code, or give me an example of how it could be used?

I'm new to programming in general so sorry if this is 'easy'.

Here is the code:

$.validator.addMethod('regexp', function(value, element, param) {
    return this.optional(element) || value.match(param);
},
'This value doesn\'t match the acceptable pattern.');

$('form').validate({
  rules: {
        password: {
              required: true,
              regexp: /^[A-Za-z\d]+$/i
        }
  }
});
gen_Eric
  • 223,194
  • 41
  • 299
  • 337
JoMojo
  • 404
  • 1
  • 7
  • 22
  • Possible duplicate: http://stackoverflow.com/questions/1053618/using-the-jquery-validation-plugin-how-can-i-add-a-regex-validation-on-a-textbo – BartekR Jan 06 '12 at 18:26

1 Answers1

0

In the rules object, the key is the name of the element. Make sure in your form, your element looks like this:

<input name="password" />
gen_Eric
  • 223,194
  • 41
  • 299
  • 337
  • Thank you Rocket for your prompt reply... I've tried your suggestion without any luck. What about the $('form') shouldn't that be the name or id of the form I'm using? And if so shouldn't it be $(#'form')? And the input should havd a class='requested' added? – JoMojo Jan 06 '12 at 21:23
  • 1
    I found my problem... the code above works great, problem was with another section of code that I had... here's the code that was causing the conflict... though honestly for now I have no idea why. var validator = $("#options").bind("invalid-form.validate", function() { $("#summary").html("Your form contains " + validator.numberOfInvalids() + " errors."); }).validate({ }); – JoMojo Jan 06 '12 at 23:23
  • Maybe `$("#options").validate({})` was somehow overwriting the settings for the validator? I dunno. – gen_Eric Jan 09 '12 at 02:45