0

I am very new to jQuery Validation will someone please correct me in where I am going wrong with the rule I am trying to add.

<script>
     $("#form").validate({
         focusInvalid: false,
    rules: {
        ownership: {
            required: true
        },
        vin: {
            required: true,
            validateVin: true
        },
        // Same for other fields
    },
    messages: {
        ownership: "This field is required.",
        vin: "Invalid VIN",
        // Repeat for other fields
    }
});

// create your custom rule
jQuery.validator.addMethod(validateVin(this.value, Number($("#vehicleyear").val()))) {
    function validateVin(vin, date) {
        var re;
        if (date >= 1981) {
            re = new RegExp("^[A-HJ-NPR-Z\\d]{8}[\\dX][A-HJ-NPR-Z\\d]{2}\\d{6}$");
        } else if (date < 1981) {
            re = new RegExp("^[A-Z\\d]{2,17}$");
        } else {
        }
        return vin.match(re);
    }, 'Please enter valid VIN.'});
</script>

This is supposed to check two fields, first it checks to see what year is picked vehicleyear then depending on the year it checks an input vin to see if the regEx matches. If it does not match correctly then it should say invalid vin.

When I run mine it does not even use the regEx but I cannot figure out why. Any help with this would be greatly appreciated!

Sparky
  • 98,165
  • 25
  • 199
  • 285
Vicki
  • 1,386
  • 4
  • 15
  • 30

1 Answers1

1

The addMethod function takes two inputs, the first is the name of the rule you are adding. The second is the function itself which does not need naming. The following code should do what you are hoping for. The only bit to be careful of is how the date variable is set. See this page for more examples. jQuery Validator addMethod()

jQuery.validator.addMethod("validateVin", function(vin) {
  var date = Number($("#vehicleyear").val());
  var re;
  if (date >= 1981) {
    re = new RegExp("^[A-HJ-NPR-Z\\d]{8}[\\dX][A-HJ-NPR-Z\\d]{2}\\d{6}$");
  } else if (date < 1981) {
    re = new RegExp("^[A-Z\\d]{2,17}$");
  } else {}
  return vin.match(re);
}, 'Please enter valid VIN.');
Sparky
  • 98,165
  • 25
  • 199
  • 285
wnbates
  • 743
  • 7
  • 16
  • Please don't use the code snippet feature for cases where you don't have enough code to run. Thanks. – Sparky Feb 08 '15 at 17:07
  • Actually, the `.addMethod()` method takes a THIRD input... the third is optional and it's the custom message. – Sparky Feb 08 '15 at 18:02