Tony D.
Tony D.

Reputation: 560

jQuery Validate custom method not working correctly

Can someone explain to me why this is not hitting my helper function? Not sure if it's a syntax thing or what..

jQuery.validator.addMethod("expDateExistInPast", function (value) {
    return customFunction(value);
}, "Expiration cannot exist in past.");

$("form[name='myForm']").validate({
 rules: {
    exp: {expDateExistInPast: true}
 }, 
 messages: {
     exp: {
        required: "message", 
        expDateExistInPast: "otherMsg"
    }
 }, 
  submitHandler: function (form) {
       form.submit();
  }
})


function customFunction(value) {
    alert("magic here");
}

UPDATE - Adding HTML

<input class="myClass" type="text" name="expiration" id="exp" maxlength="4" pattern="^(0[1-9]|1[0-2])[0-9][0-9]$" required="" placeholder="MMYY" aria-required="true" aria-invalid="true">

Upvotes: 0

Views: 211

Answers (1)

Sparky
Sparky

Reputation: 98718

Your input contains name="expiration"...

<input class="myClass" type="text" name="expiration" id="exp" maxlength="4" pattern="^(0[1-9]|1[0-2])[0-9][0-9]$" required="" placeholder="MMYY" aria-required="true" aria-invalid="true">

However, the problem is that your .validate() method is using exp within the rules object...

rules: {
    exp: {
        expDateExistInPast: true
    }
},

You must only use the name attribute here...

rules: {
    expiration: { // <- this is the NAME of the input
        expDateExistInPast: true
    }
},

Working: jsfiddle.net/se4dc18h/

Upvotes: 1

Related Questions