【问题标题】:jquery name validation using plugin使用插件的 jquery 名称验证
【发布时间】:2017-03-18 05:10:49
【问题描述】:

我正在尝试验证用户的名字,使其只接受字符。我还想指定一个最大长度验证,名字不能为空。

但我只能对字符进行验证。现在我想设置名字的最大长度,并且当验证失败时,名字也不应该为空,它应该将输入框的边框颜色更改为红色并给出错误消息。

$(document).ready(function(){
  jQuery.validator.addMethod("lettersonly", function(value, element) {
     return this.optional(element) || /^[a-z\s]+$/i.test(value);
  });

  $('#myForm').validate({
    rules: {
        firstName: {
            lettersonly: true

        }
    },
    messages:{
        firstName: {
            lettersonly: "please enter characters only",
        }
    }
  });
});
.error{
   color:red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.15.0/jquery.validate.min.js"></script>
<script src="http://ajax.microsoft.com/ajax/jquery.validate/1.7/additional-methods.js"></script>


 <form id="myForm">
   <label for="firstname" id="label1">firstName:</label>
   <input type="text"id="firstName" name="firstName"><br><br>
</form>

【问题讨论】:

  • 极度懒惰,没有阅读清楚列出所有规则和方法的参考资料。

标签: jquery forms jquery-validate


【解决方案1】:

您可以在 jquery-validation 插件中使用内置函数。

https://jqueryvalidation.org/maxlength-method/

如果元素是,则返回 false

  • 某种文本输入,其值过长
  • 一组选中的复选框过多的复选框
  • 一个选择并且选择了太多选项

Live demo

$('#myForm').validate({
rules: {
    firstName: {
        lettersonly: true
        required: true,
        maxlength: 200
    }
},
messages:{
    firstName: {
        lettersonly: "please enter characters only",
        required: "Enter your first name, please.",
        maxlength: "Funny msg"
    }
}
});

【讨论】:

  • 如果产生错误,如何将边框颜色更改为红色
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-02-06
  • 2012-04-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多