一、官网地址:http://bassistance.de/jquery-plugins/jquery-plugin-validation
二、默认校验规则
(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
三、默认的提示
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}.")
},
四、Jquery Validate 自定义验证规则
addMethod(name,method,message)方法
参数 name 是添加的方法的名字。
参数 method 是一个函数,接收三个参数 (value,element,param) 。
value 是元素的值,element 是元素本身,param 是参数。
身份证号码验证
jQuery.validator.addMethod(“idcardno”, function(value, element) { return this.optional(element) || isIdCardNo(value); }, “请正确输入身份证号码”);
字母数字
jQuery.validator.addMethod(“alnum”, function(value, element) { return this.optional(element) || /^[a-zA-Z0-9]+$/.test(value); }, “只能包括英文字母和数字”);
邮政编码验证
jQuery.validator.addMethod(“zipcode”, function(value, element) { var tel = /^[0-9]{ 6}$/; return this.optional(element) || (tel.test(value)); }, “请正确填写邮政编码”);
汉字
jQuery.validator.addMethod(“chcharacter”, function(value, element) { var tel = /^[u4e00-u9fa5]+$/; return this.optional(element) || (tel.test(value)); }, “请输入汉字”);
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 }!”));
字符最大长度验证(一个中文字符长度为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 }!”));
字符验证
jQuery.validator.addMethod(“string”, function(value, element) { return this.optional(element) || /^[u0391-uFFE5w]+$/.test(value); }, “不允许包含特殊符号!”);
手机号码验证
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)); }, “手机号码格式错误!”);
电话号码验证
jQuery.validator.addMethod(“phone”, function(value, element) { var tel = /^(d{ 3,4}-?)?d{ 7,9}$/g; return this.optional(element) || (tel.test(value)); }, “电话号码格式错误!”);
必须以特定字符串开头验证
jQuery.validator.addMethod(“begin”, function(value, element, param) { var begin = new RegExp(“ ^ ”+param); return this.optional(element) || (begin.test(value)); }, $.validator.format(“必须以 { 0 } 开头!”));
验证两次输入值是否不相同
jQuery.validator.addMethod(“notEqualTo”, function(value, element, param) { return value != $(param).val(); }, $.validator.format(“两次输入不能相同!”));
验证值不允许与特定值等于
jQuery.validator.addMethod(“notEqual”, function(value, element, param) { return value != param; }, $.validator.format(“输入值不允许为 { 0 }!”));
验证值必须大于特定值(不能等于)
jQuery.validator.addMethod(“gt”, function(value, element, param) { return value > param; }, $.validator.format(“输入值必须大于 { 0 }!”));
小数点前最多9位,小数点后最多6位
jQuery.validator.addMethod("decimal", function (value, element) { return this.optional(element) || /^([1-9]\d{ 0,8}|0)(\.\d{ 1,6})?$/.test(value); }, "小数点前最多9位,小数点后最多6位^_^");
结束时间不能小于开始时间
jQuery.validator.addMethod("laterTo", function (value, element, param) { return $(param).val().split("-").join("") < $(element).val().split("-").join(""); }, "结束时间不能小于开始时间^_^");
<!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="重置"> <input type="submit" value="提交">
</form>
</body>
</html>
微软隐式校验:
一、实体特性标签
//------------------------------------------------------------------------------
// <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; }
}
}
二、添加强类型视图(添加)模型类和实体类保持一致
三,视图页面引用jQuery,jQuery-Validate,jQuery-Validate-unobtrusive三个JS文件
@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>