JQuery-Validate- (Microsoft implicit validation) default validation rules and commonly used custom validation rules

1. Official website address: http://bassistance.de/jquery-plugins/jquery-plugin-validation

Two, the default verification rules

(1)、required:true               必输字段
(2)、remote:"remote-valid.jsp"   使用ajax方法调用remote-valid.jsp验证输入值
(3)、email:true                  必须输入正确格式的电子邮件
(4)、url:true                    必须输入正确格式的网址
(5)、date:true                   必须输入正确格式的日期,日期校验ie6出错,慎用
(6)、dateISO:true                必须输入正确格式的日期(ISO),例如:2009-06-23,1998/01/22 只验证格式,不验证有效性
(7)、number:true                 必须输入合法的数字(负数,小数)
(8)、digits:true                 必须输入整数
(9)、creditcard:true             必须输入合法的信用卡号
(10)、equalTo:"#password"        输入值必须和#password相同
(11)、accept:                    输入拥有合法后缀名的字符串(上传文件的后缀)
(12)、maxlength:5                输入长度最多是5的字符串(汉字算一个字符)
(13)、minlength:10               输入长度最小是10的字符串(汉字算一个字符)
(14)、rangelength:[5,10]         输入长度必须介于 5 和 10 之间的字符串")(汉字算一个字符)
(15)、range:[5,10]               输入值必须介于 5 和 10 之间
(16)、max:5                      输入值不能大于5
(17)、min:10                     输入值不能小于10

Three, the default prompt

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).",
dateDE: "Bitte geben Sie ein g眉ltiges Datum ein.",
number: "Please enter a valid number.",
numberDE: "Bitte geben Sie eine Nummer ein.",
digits: "Please enter only digits",
creditcard: "Please enter a valid credit card number.",
equalTo: "Please enter the same value again.",
accept: "Please enter a value with a valid extension.",
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}.")
},

Four, Jquery  Validate  custom validation rules

addMethod(name,method,message)方法

The parameter name is the name of the added method.

The parameter method is a function that receives three parameters (value, element, param).

value is the value of the element, element is the element itself, and param is the parameter.

 

 ID verification

jQuery.validator.addMethod("idcardno", function(value, element) { 
            return this.optional(element) || isIdCardNo(value); 
        }, "Please enter the ID card number correctly");

letter and number

jQuery.validator.addMethod("alnum", function(value, element) { 
            return this.optional(element) || /^[a-zA-Z0-9]+$/.test(value); 
        }, "Only Can include English letters and numbers");

 Postal code verification

jQuery.validator.addMethod(“zipcode”, function(value, element) { 
            var tel = /^[0-9]{ 
   
   6}$/; 
            return this.optional(element) || (tel.test(value)) ; 
        }, "Please fill in the postal code correctly");

Chinese character

jQuery.validator.addMethod("chcharacter", function(value, element) { 
            var tel = /^[u4e00-u9fa5]+$/; 
            return this.optional(element) || (tel.test(value)); 
        } , "Please enter Chinese characters");

Character minimum length verification (one ChineseThe character length is 2)

jQuery.validator.addMethod(“stringMinLength”, function(value, element, param) {
            var length = value.length;
            for(var i = 0; i < value.length; i++) {
                if(value.charCodeAt(i) > 127) {
                    length++;
                }
            }
            return this.optional(element) || (length >= param);
        }, $.validator.format(“长度不能小于 { 0 }!”));

Maximum character length verification (a Chinese character length is 2)

jQuery.validator.addMethod(“stringMaxLength”, function(value, element, param) {
            var length = value.length;
            for(var i = 0; i < value.length; i++) {
                if(value.charCodeAt(i) > 127) {
                    length++;
                }
            }
            return this.optional(element) || (length <= param);
        }, $.validator.format(“长度不能大于 { 0 }!”));

Character verification

jQuery.validator.addMethod("string", function(value, element) { 
            return this.optional(element) || /^[u0391-uFFE5w]+$/.test(value); 
        }, "Special symbols are not allowed !");

Mobile phone number verification

jQuery.validator.addMethod(“mobile”, function(value, element) {
            var length = value.length;
            return this.optional(element) || (length == 11 && /^(((13[0-9]{
   
   1})|(15[0-9]{
   
   1}))+d{
   
   8})$/.test(value));
        }, “手机号码格式错误!”);

Phone number verification

jQuery.validator.addMethod(“phone”, function(value, element) { 
            var tel = /^(d{ 
   
   3,4}-?)?d{
    
   7,9}$/g; 
            return this.optional(element) || (tel.test(value)); 
        }, "The phone number format is wrong!");

Must start with a specific string to verify

jQuery.validator.addMethod(“begin”, function(value, element, param) {
            var begin = new RegExp(“ ^ ”+param);
            return this.optional(element) || (begin.test(value));
        }, $.validator.format(“必须以 { 0 } 开头!”));

 Verify that the two input values ​​are not the same

jQuery.validator.addMethod("notEqualTo", function(value, element, param) { 
            return value != $(param).val(); 
        }, $.validator.format("The two inputs cannot be the same!")) ;

 The verification value is not allowed to be equal to the specified value

jQuery.validator.addMethod("notEqual", function(value, element, param) { 
            return value != param; 
        }, $.validator.format("The input value is not allowed to be {0 }!"));

The verification value must be greater than a specific value (not equal to)

jQuery.validator.addMethod("gt", function(value, element, param) { 
            return value> param; 
        }, $.validator.format("The input value must be greater than {0 }!"));

Up to 9 digits before the decimal point and 6 digits after the decimal point

jQuery.validator.addMethod("decimal", function (value, element) { 
    return this.optional(element) || /^([1-9]\d{ 
   
   0,8}|0)(\.\d{
    
   1,6})?$/.test(value); 
}, "Up to 9 digits before the decimal point and 6 digits after the decimal point^_^");

The end time cannot be less than the start time

jQuery.validator.addMethod("laterTo", function (value, element, param) { 
    return $(param).val().split("-").join("") <$(element).val() .split("-").join(""); 
}, "The end time cannot be less than the start time^_^");

 

 

 

 

 

 


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>jQuery验证</title>
    <script src="scripts/jquery-3.4.1.js"></script>
    <script src="scripts/jquery.validate.js"></script>
    <script>
        $(function(){
    
    
            $('#frmUserLogin').validate({
    
    
                rules:{
    
    
                    txtName:{
    
    
                        required:true,
                        maxlength:5,
                    },
                    txtPwd:{
    
    
                        required:true,
                        minlength:6,
                        number:true
                    },
                    txtEmail:{
    
    
                        required:true,
                        email:true,
                    }  
                },
                messages:{
    
    
                    txtName:{
    
    
                        required:"*必选项",
                        maxlength:"*超出长度"
                    },
                    txtPwd:{
    
    
                        required:"*必填项",
                        minlength:"*密码长度过少",
                        number:"*格式错误(数字)"
                    },
                    txtEmail:{
    
    
                        required:"*必填项",
                        email:"*邮箱格式错误"
                    }
                }
            })
        })
    </script>
    <!-- 为错误信息提示设置样式 -->
    <style>
        #txtName-error{
    
    
            color:red;
        }
        #txtPwd-error{
    
    
            color:red;
        }
        #txtEmail-error{
    
    
            color:red;
        }
    </style>
</head>
<body>
    <form action="#" id="frmUserLogin">
        用户名:<input type="text" name="txtName"><br>
        密码:<input type="password" name="txtPwd"><br>
        邮箱:<input type="email" name="txtEmail"><br><br>
        <input type="reset" value="重置">&nbsp;&nbsp;&nbsp;<input type="submit" value="提交"> 
    </form>
</body>
</html>

Microsoft implicit check:
1. Entity feature label

//------------------------------------------------------------------------------
// <auto-generated>
//     此代码已从模板生成。
//
//     手动更改此文件可能导致应用程序出现意外的行为。
//     如果重新生成代码,将覆盖对此文件的手动更改。
// </auto-generated>
//------------------------------------------------------------------------------

namespace MyFirstMvcManager
{
    
    
    using System;
    using System.Collections.Generic;
    using System.ComponentModel.DataAnnotations;

    public partial class studentInfo
    {
    
    
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
        public studentInfo()
        {
    
    
            this.selectInfoes = new HashSet<selectInfo>();
        }
    
        [Required(AllowEmptyStrings =false,ErrorMessage ="*必填项")]
        public string stuID {
    
     get; set; }
        [Required(AllowEmptyStrings = false, ErrorMessage = "*必填项")]
        [MaxLength(5,ErrorMessage ="*超出最大长度")]
        public string stuName {
    
     get; set; }
        [Required(AllowEmptyStrings = false, ErrorMessage = "*必填项")]
        [RegularExpression("[男女]",ErrorMessage ="*男女")]
        public string stuSex {
    
     get; set; }
        [Required(AllowEmptyStrings = false, ErrorMessage = "*必填项")]
        [Range(18,40,ErrorMessage ="*年龄超出范围")]
        public Nullable<int> stuAge {
    
     get; set; }
        [Required(AllowEmptyStrings = false, ErrorMessage = "*必填项")]
        [RegularExpression(@"\d{11}", ErrorMessage = "*手机号不符合规范")]
        public string stuTel {
    
     get; set; }
        [Required(AllowEmptyStrings = false, ErrorMessage = "*必填项")] 
        public string stuDorm {
    
     get; set; }
    
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
        public virtual ICollection<selectInfo> selectInfoes {
    
     get; set; }
    }
}

2. Add a strongly typed view (add) The model class is consistent with the entity class.
3. The view page refers to three JS files: jQuery, jQuery-Validate, and jQuery-Validate-unobtrusive

@model MyFirstMvcManager.studentInfo

@{
    
    
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Add</title>
    <script src="~/Scripts/jquery-3.3.1.js"></script>
    <script src="~/Scripts/jquery.validate.js"></script>
    <script src="~/Scripts/jquery.validate.unobtrusive.js"></script>
    <style>
        /*错误消息样式*/
        .text-danger{
    
    
            color:red;
        }
    </style>
</head>
<body>
    @using (Html.BeginForm()) 
    {
    
    
        @Html.AntiForgeryToken()
        
        <div class="form-horizontal">
            <h4>studentInfo</h4>
            <hr />
            @Html.ValidationSummary(true, "", new {
    
     @class = "text-danger" })
            <div class="form-group">
                @Html.LabelFor(model => model.stuID, htmlAttributes: new {
    
     @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.EditorFor(model => model.stuID, new {
    
     htmlAttributes = new {
    
     @class = "form-control" } })
                    @Html.ValidationMessageFor(model => model.stuID, "", new {
    
     @class = "text-danger" })
                </div>
            </div>
    
            <div class="form-group">
                @Html.LabelFor(model => model.stuName, htmlAttributes: new {
    
     @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.EditorFor(model => model.stuName, new {
    
     htmlAttributes = new {
    
     @class = "form-control" } })
                    @Html.ValidationMessageFor(model => model.stuName, "", new {
    
     @class = "text-danger" })
                </div>
            </div>
    
            <div class="form-group">
                @Html.LabelFor(model => model.stuSex, htmlAttributes: new {
    
     @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.EditorFor(model => model.stuSex, new {
    
     htmlAttributes = new {
    
     @class = "form-control" } })
                    @Html.ValidationMessageFor(model => model.stuSex, "", new {
    
     @class = "text-danger" })
                </div>
            </div>
    
            <div class="form-group">
                @Html.LabelFor(model => model.stuAge, htmlAttributes: new {
    
     @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.EditorFor(model => model.stuAge, new {
    
     htmlAttributes = new {
    
     @class = "form-control" } })
                    @Html.ValidationMessageFor(model => model.stuAge, "", new {
    
     @class = "text-danger" })
                </div>
            </div>
    
            <div class="form-group">
                @Html.LabelFor(model => model.stuTel, htmlAttributes: new {
    
     @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.EditorFor(model => model.stuTel, new {
    
     htmlAttributes = new {
    
     @class = "form-control" } })
                    @Html.ValidationMessageFor(model => model.stuTel, "", new {
    
     @class = "text-danger" })
                </div>
            </div>
    
            <div class="form-group">
                @Html.LabelFor(model => model.stuDorm, htmlAttributes: new {
    
     @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.EditorFor(model => model.stuDorm, new {
    
     htmlAttributes = new {
    
     @class = "form-control" } })
                    @Html.ValidationMessageFor(model => model.stuDorm, "", new {
    
     @class = "text-danger" })
                </div>
            </div>
    
            <div class="form-group">
                <div class="col-md-offset-2 col-md-10">
                    <input type="submit" value="Create" class="btn btn-default" />
                </div>
            </div>
        </div>
    }
    
    <div>
        @Html.ActionLink("Back to List", "Index")
    </div>
</body>
</html>

Insert picture description here

Guess you like

Origin blog.csdn.net/MrLsss/article/details/106630013