Prasanna Manian
Prasanna Manian

Reputation: 1

JQueryValidation with custom message and custom method

I am trying to do a form validation with jQueryValidation plugin. I have defined custom message for the field and also I have a custom method validation.

It looks like it always shows the custom message and ignore the custom validation error message.

Code

<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="//code.jquery.com/jquery-1.11.0.js"></script>
<script type="text/javascript" src="https://ajax.aspnetcdn.com/ajax/jquery.validate/1.14.0/jquery.validate.js"></script>
<script type='text/javascript'>//<![CDATA[
$(document).ready(function() {
  $.validator.addMethod("strlength", function (elemVal, element) {
    if(elemVal.length > 5) {
      return true;      
    } else {
      return false;
    }
  }, 'Enter atleast 6 characters');

    $("#sampleForm").validate({
    messages: {
        "firstname": "Please enter the firstname"
    },
        rules: {
        "firstname": {
        required: true,
        strlength: true
      }
    }
    });
});
//]]>
</script>
</head>
<body>
  <form name="sampleForm" id="sampleForm" method="post" action="">
  <p>
    <label>Enter Firstname</label>
    <input type="text" name="firstname" id="firstname" value=""/>  
  </p>
  <p>
    <input class="submit" type="submit" value="Submit">
  </p>
</form>
</body>
</html>

I have create the sample code here https://jsfiddle.net/manianprasanna/xhq8xtuk/14/

Upvotes: 0

Views: 60

Answers (1)

Rayon
Rayon

Reputation: 36609

You need to define messages for specific validator. Define firstName as object which will accept keys as your validation parameters.

Try this:

$(document).ready(function() {

  $.validator.addMethod("strlength", function(elemVal, element) {
    if (elemVal.length > 5) {
      return true;
    } else {
      return false;
    }
  }, 'Enter atleast 6 characters');

  console.info('testing');

  $("#sampleForm").validate({
    messages: {
      "firstname": {
        required: "Please enter the firstname"
      }
    },
    rules: {
      "firstname": {
        required: true,
        strlength: true
      }
    }
  });

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="https://ajax.aspnetcdn.com/ajax/jquery.validate/1.14.0/jquery.validate.js"></script>
<form name="sampleForm" id="sampleForm" method="post" action="">
  <p>
    <label>Enter Firstname</label>
    <input type="text" name="firstname" id="firstname" value="" />
  </p>
  <p>
    <input class="submit" type="submit" value="Submit">
  </p>
</form>

Fiddle here

Upvotes: 1

Related Questions