Home >Web Front-end >Front-end Q&A >What is jquery-validate

What is jquery-validate

青灯夜游
青灯夜游Original
2022-05-16 12:17:181735browse

jquery-validate refers to the form validation plug-in. It is a validation plug-in developed based on jquery. It provides powerful validation functions for forms and makes client-side form validation easier; the plug-in bundles a set of useful Verification methods, including URL and email verification, while providing an API for writing user-defined methods.

What is jquery-validate

The operating environment of this tutorial: windows7 system, jquery2.2.1&&jquery-validate1.14.0 version, Dell G3 computer.

jquery-validate refers to the form validation plug-in, which is a verification plug-in developed based on jquery.

The jQuery Validate plug-in provides powerful validation functions for forms, making client-side form validation easier, while providing a large number of customization options to meet various application needs. The plugin bundles a set of useful validation methods, including URL and email validation, and provides an API for writing user-defined methods. All bundled methods use English for error messages by default and have been translated into 37 other languages.

This plugin is written and maintained by Jörn Zaefferer, a member of the jQuery team, a lead developer on the jQuery UI team, and the maintainer of QUnit. This plugin has been around since the early days of jQuery in 2006 and has been updated ever since. The current version is 1.14.0.

Visit the jQuery Validate official website and download the latest version of the jQuery Validate plug-in.

1.14.0 version download address: http://libs.cdnjs.net/jquery-validate/1.14.0/

Import js library

<script src="http://libs.cdnjs.net/jquery/2.2.1/jquery.js" rel="external nofollow"  rel="external nofollow" ></script>
<script src="http://libs.cdnjs.net/jquery-validate/1.14.0/jquery.validate.min.js" rel="external nofollow"  rel="external nofollow" ></script>

Default verification rules

Serial number Rule Description
1 required:true Required field.
2 remote:"check.php" Use the ajax method to call check.php to verify the input value.
3 email:true Must enter a correctly formatted email.
4 url:true You must enter the URL in the correct format.
5 date:true The date must be entered in the correct format. Date verification ie6 error, use with caution.
6 dateISO:true The date (ISO) in the correct format must be entered, for example: 2009-06-23, 1998/01/ twenty two. Only the format is verified, not the validity.
7 number:true Must enter a legal number (negative number, decimal).
8 digits:true Must enter an integer.
9 creditcard: Must enter a legal credit card number.
10 equalTo:"#field" The input value must be the same as #field.
11 accept: Enter a string with a legal suffix (the suffix of the uploaded file).
12 maxlength:5 Enter a string with a maximum length of 5 (Chinese characters count as one character).
13 minlength:10 Enter a string with a minimum length of 10 (Chinese characters count as one character).
14 rangelength:[5,10] The input length must be between 5 and 10 (Chinese characters count as one character ).
15 range:[5,10] The input value must be between 5 and 10.
16 max:5 The input value cannot be greater than 5.
17 min:10 The input value cannot be less than 10.

默认提示

messages: {
    required: "This field is required.",
    remote: "Please fix this field.",
    email: "Please enter a valid email address.",
    url: "Please enter a valid URL.",
    date: "Please enter a valid date.",
    dateISO: "Please enter a valid date ( ISO ).",
    number: "Please enter a valid number.",
    digits: "Please enter only digits.",
    creditcard: "Please enter a valid credit card number.",
    equalTo: "Please enter the same value again.",
    maxlength: $.validator.format( "Please enter no more than {0} characters." ),
    minlength: $.validator.format( "Please enter at least {0} characters." ),
    rangelength: $.validator.format( "Please enter a value between {0} and {1} characters long." ),
    range: $.validator.format( "Please enter a value between {0} and {1}." ),
    max: $.validator.format( "Please enter a value less than or equal to {0}." ),
    min: $.validator.format( "Please enter a value greater than or equal to {0}." )
}

jQuery Validate提供了中文信息提示包,位于下载包的 /localization/messages_zh.js,内容如下:

(function( factory ) {
    if ( typeof define === "function" && define.amd ) {
        define( ["jquery", "../jquery.validate"], factory );
    } else {
        factory( jQuery );
    }
}(function( $ ) {
/*
 * Translated default messages for the jQuery validation plugin.
 * Locale: ZH (Chinese, 中文 (Zhōngwén), 汉语, 漢語)
 */
$.extend($.validator.messages, {
    required: "这是必填字段",
    remote: "请修正此字段",
    email: "请输入有效的电子邮件地址",
    url: "请输入有效的网址",
    date: "请输入有效的日期",
    dateISO: "请输入有效的日期 (YYYY-MM-DD)",
    number: "请输入有效的数字",
    digits: "只能输入数字",
    creditcard: "请输入有效的信用卡号码",
    equalTo: "你的输入不相同",
    extension: "请输入有效的后缀",
    maxlength: $.validator.format("最多可以输入 {0} 个字符"),
    minlength: $.validator.format("最少要输入 {0} 个字符"),
    rangelength: $.validator.format("请输入长度在 {0} 到 {1} 之间的字符串"),
    range: $.validator.format("请输入范围在 {0} 到 {1} 之间的数值"),
    max: $.validator.format("请输入不大于 {0} 的数值"),
    min: $.validator.format("请输入不小于 {0} 的数值")
});
}));

你可以将该本地化信息文件 /localization/messages_zh.js 引入到页面:

<script src="http://libs.cdnjs.net/jquery-validate/1.14.0/localization/messages_zh.js" rel="external nofollow"  rel="external nofollow" ></script>

使用方式

1、将校验规则写到控件中

<script src="http://libs.cdnjs.net/jquery/2.2.1/jquery.js" rel="external nofollow"  rel="external nofollow" ></script>
<script src="http://libs.cdnjs.net/jquery-validate/1.14.0/jquery.validate.min.js" rel="external nofollow"  rel="external nofollow" ></script>
<script src="http://libs.cdnjs.net/jquery-validate/1.14.0/localization/messages_zh.js" rel="external nofollow"  rel="external nofollow" ></script>
<script>
$.validator.setDefaults({
    submitHandler: function() {
      alert("提交事件!");
    }
});
$().ready(function() {
    $("#commentForm").validate();
});
</script>
输入您的名字,邮箱,URL,备注。

2、将校验规则写到 js 代码中

$().ready(function() {
// 在键盘按下并释放及提交后验证提交表单
  $("#signupForm").validate({
    rules: {
      firstname: "required",
      lastname: "required",
      username: {
        required: true,
        minlength: 2
      },
      password: {
        required: true,
        minlength: 5
      },
      confirm_password: {
        required: true,
        minlength: 5,
        equalTo: "#password"
      },
      email: {
        required: true,
        email: true
      },
      topic: {
        required: "#newsletter:checked",
        minlength: 2
      },
      agree: "required"
    },
    messages: {
      firstname: "请输入您的名字",
      lastname: "请输入您的姓氏",
      username: {
        required: "请输入用户名",
        minlength: "用户名必需由两个字母组成"
      },
      password: {
        required: "请输入密码",
        minlength: "密码长度不能小于 5 个字母"
      },
      confirm_password: {
        required: "请输入密码",
        minlength: "密码长度不能小于 5 个字母",
        equalTo: "两次密码输入不一致"
      },
      email: "请输入一个正确的邮箱",
      agree: "请接受我们的声明",
      topic: "请选择两个主题"
     }
    })
});

messages 处,如果某个控件没有 message,将调用默认的信息

<form class="cmxform" id="signupForm" method="get" action="">
  <fieldset>
    <legend>验证完整的表单</legend>
    <p>
      <label for="firstname">名字</label>
      <input id="firstname" name="firstname" type="text">
    </p>
    <p>
      <label for="lastname">姓氏</label>
      <input id="lastname" name="lastname" type="text">
    </p>
    <p>
      <label for="username">用户名</label>
      <input id="username" name="username" type="text">
    </p>
    <p>
      <label for="password">密码</label>
      <input id="password" name="password" type="password">
    </p>
    <p>
      <label for="confirm_password">验证密码</label>
      <input id="confirm_password" name="confirm_password" type="password">
    </p>
    <p>
      <label for="email">Email</label>
      <input id="email" name="email" type="email">
    </p>
    <p>
      <label for="agree">请同意我们的声明</label>
      <input type="checkbox" class="checkbox" id="agree" name="agree">
    </p>
    <p>
      <label for="newsletter">我乐意接收新信息</label>
      <input type="checkbox" class="checkbox" id="newsletter" name="newsletter">
    </p>
    <fieldset id="newsletter_topics">
      <legend>主题 (至少选择两个) - 注意:如果没有勾选“我乐意接收新信息”以下选项会隐藏,但我们这里作为演示让它可见</legend>
      <label for="topic_marketflash">
        <input type="checkbox" id="topic_marketflash" value="marketflash" name="topic">Marketflash
      </label>
      <label for="topic_fuzz">
        <input type="checkbox" id="topic_fuzz" value="fuzz" name="topic">Latest fuzz
      </label>
      <label for="topic_digester">
        <input type="checkbox" id="topic_digester" value="digester" name="topic">Mailing list digester
      </label>
      <label for="topic" class="error">Please select at least two topics you&#39;d like to receive.</label>
    </fieldset>
    <p>
      <input class="submit" type="submit" value="提交">
    </p>
  </fieldset>
</form>

说明:

  • required: true 值是必须的。

  • required: "#aa:checked" 表达式的值为真,则需要验证。

  • required: function(){} 返回为真,表示需要验证。

后边两种常用于,表单中需要同时填或不填的元素。

常用方法及注意问题

1、用其他方式替代默认的 SUBMIT

$().ready(function() {
 $("#signupForm").validate({
        submitHandler:function(form){
            alert("提交事件!");   
            form.submit();
        }    
    });
});

使用 ajax 方式

$(".selector").validate({     
 submitHandler: function(form) 
   {      
      $(form).ajaxSubmit();     
   }  
 })

可以设置 validate 的默认值,写法如下:

$.validator.setDefaults({
  submitHandler: function(form) { alert("提交事件!");form.submit(); }
});

如果想提交表单, 需要使用 form.submit(),而不要使用 $(form).submit()。

2、debug,只验证不提交表单

如果这个参数为true,那么表单不会提交,只进行检查,调试时十分方便。

$().ready(function() {
 $("#signupForm").validate({
        debug:true
    });
});

如果一个页面中有多个表单都想设置成为 debug,则使用:

$.validator.setDefaults({
   debug: true
})

3、ignore:忽略某些元素不验证

ignore: ".ignore"

4、更改错误信息显示的位置

errorPlacement:Callback

指明错误放置的位置,默认情况是:error.appendTo(element.parent());即把错误信息放在验证的元素后面。

errorPlacement: function(error, element) {  
    error.appendTo(element.parent());  
}

【推荐学习:jQuery视频教程web前端视频

The above is the detailed content of What is jquery-validate. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:What is jquery-formNext article:What is jquery-form