JQueryValidation包含自定义消息和自定义方法

时间:2016-01-10 02:27:22

标签: javascript jquery jquery-validate

我正在尝试使用jQueryValidation插件进行表单验证。我已为该字段定义了自定义消息,并且我还有自定义方法验证。

它看起来总是显示自定义消息并忽略自定义验证错误消息。

代码

<!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>

我在这里创建了示例代码https://jsfiddle.net/manianprasanna/xhq8xtuk/14/

1 个答案:

答案 0 :(得分:1)

您需要为特定messages定义validator。将firstName定义为object,它将接受密钥作为validation参数。

试试这个:

&#13;
&#13;
$(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
      }
    }
  });

});
&#13;
<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>
&#13;
&#13;
&#13;

Fiddle here