博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
ASP.NET MVC验证 - 自定义验证规则、验证2个属性值不等【待验证】
阅读量:7228 次
发布时间:2019-06-29

本文共 4484 字,大约阅读时间需要 14 分钟。

提示:保存后才提示错误信息

 

自定义验证特性,继承ValidationAttribute并实现IClientValidatable

这次重写了基类的IsValid()方法的另外一个重载,因为该重载包含了验证上下文ValidationContext,从中可以获取属性及属性值。

using System.ComponentModel.DataAnnotations;using System.Globalization;using System.Web.Mvc;namespace MvcValidation.Extension{    public class NotEqualToAttribute : ValidationAttribute,IClientValidatable    {        public string OtherProperty { get; set; }        public NotEqualToAttribute(string otherProperty)        {            OtherProperty = otherProperty;        }        protected override ValidationResult IsValid(object value, ValidationContext validationContext)        {            //从验证上下文中可以获取我们想要的的属性            var property = validationContext.ObjectType.GetProperty(OtherProperty);            if (property == null)            {                return new ValidationResult(string.Format(CultureInfo.CurrentCulture, "{0} 不存在", OtherProperty));            }            //获取属性的值            var otherValue = property.GetValue(validationContext.ObjectInstance, null);            if (object.Equals(value, otherValue))            {                return new ValidationResult(FormatErrorMessage(validationContext.DisplayName));            }            return null;        }        public System.Collections.Generic.IEnumerable
GetClientValidationRules(ModelMetadata metadata, ControllerContext context) { var rule = new ModelClientValidationRule { ValidationType = "notequalto", ErrorMessage = FormatErrorMessage(metadata.GetDisplayName()) }; rule.ValidationParameters["other"] = OtherProperty; yield return rule; } }}

  View model

[NotEqualTo("UserName", ErrorMessage = "不能与用户名的值相同")]用来比较属性UserName的值。

public class RegisterModel    {        [Required]        [StringLength(6, MinimumLength = 2)] //加        [Display(Name = "用户名")]        //[Remote("CheckUserName","Validate", ErrorMessage = "远程验证用户名失败")]        [NoInput("demo,jack",ErrorMessage = "不能使用此名称")]        public string UserName { get; set; }        [Required]        [DataType(DataType.EmailAddress)]        [Display(Name = "邮件")]        //[Email]        public string Email { get; set; }        [Required]        [StringLength(100, ErrorMessage = "{0}栏位最少{2}个字,最多{1}个字", MinimumLength = 6)]        [DataType(DataType.Password)]        [Display(Name = "密码")]        public string Password { get; set; }        [DataType(DataType.Password)]        [Display(Name = "确认密码")]        [System.ComponentModel.DataAnnotations.Compare("Password", ErrorMessage = "密码和确认密码不匹配。")]        public string ConfirmPassword { get; set; }        [NotEqualTo("UserName", ErrorMessage = "不能与用户名的值相同")]        public string OtherName { get; set; }    }

 在mvc中,密码比较使用

[System.Web.Mvc.Compare("Password", ErrorMessage = "密码和确认密码不匹配。")]

扩展jquery的验证,jQuery.validator.noteaualto.js

jQuery.validator.addMethod('notEqualTo', function(value, element, param) {
//意思是表单值为空时也能通过验证
//但,如果表单有值,就必须满足||后面的条件,否则返回false
return this.optional(element) || value != $(param).val();
});
 
//第一个参数是jquery验证扩展方法名
//第二个参数与rule.ValidationParameters["other"]中的key对应
//option是指ModelClientValidationRule对象实例
jQuery.validator.unobtrusive.adapters.add('notequalto', ['other'], function(options) {
options.rules['notEqualTo'] = '#' + options.params.other;
if (options.message) {
options.messages['notEqualTo'] = options.message;
}
});

 

  Register.cshtml视图

@model MvcValidation.Models.RegisterModel@{    ViewBag.Title = "注册";}

@ViewBag.Title.

创建新帐户。

@using (Html.BeginForm()) { @Html.AntiForgeryToken() @Html.ValidationSummary()
注册表单
  1. @Html.LabelFor(m => m.UserName) @Html.TextBoxFor(m => m.UserName)
  2. @Html.LabelFor(m => m.Email) @Html.TextBoxFor(m => m.Email)
  3. @Html.LabelFor(m => m.Password) @Html.PasswordFor(m => m.Password)
  4. @Html.LabelFor(m => m.ConfirmPassword) @Html.PasswordFor(m => m.ConfirmPassword)
  5. @Html.LabelFor(m => m.OtherName) @Html.TextBoxFor(m => m.OtherName)
}@section Scripts { @Scripts.Render("~/bundles/jqueryval") }

 

效果:

 

转自:http://www.csharpwin.com/dotnetspace/13573r4911.shtml

 

转载地址:http://yfdfm.baihongyu.com/

你可能感兴趣的文章
用ASCII码显示string.xml中的特殊字符
查看>>
网站301跳转到新域名
查看>>
codewars020: The Clockwise Spiral 数字顺时针螺旋矩阵
查看>>
ios 下拉刷新
查看>>
Django在Windows系统下的安装配置
查看>>
懒到极致:对mybatis的进一步精简
查看>>
Android学习之OTA Update
查看>>
Maven Multi-environment package
查看>>
JMM-java内存模型
查看>>
iOS的soap应用(webservice) 开发
查看>>
Delphi listview 点击列头排序
查看>>
android preference page
查看>>
mysql索引挑选
查看>>
关于冰岛足球的段子
查看>>
在 Windows 中安装 Laravel 5.1.X
查看>>
TeamViewer 9发布-在Linux下安装运行
查看>>
Centos7 Gitea安装教程 - 一款易搭建,运行快的Git服务器
查看>>
CentOS minimal 网络配置
查看>>
Nginx架构
查看>>
为什么结构体中的数组不能用const int变量指定大小?
查看>>