原文:
MVC验证05-自定义验证规则、验证2个属性值不等本文体验2个属性值不等。即当一个属性输入值,另外一个属性输入的值不能和第一个属性值相等。相关文章包括:
MVC验证01-基础、远程验证
MVC验证02-自定义验证规则、邮件验证
MVC验证03-自定义验证规则、禁止输入某些值
MVC验证04-自定义验证规则、日期范围验证
自定义验证特性,继承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<ModelClientValidationRule> 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; }
}
扩展jquery的验证,jQuery.validator.noteaualto.js
jQuery.validator.addMethod(‘notEaualTo‘, 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 = "注册";
}
<hgroup class="title">
<h1>@ViewBag.Title.</h1>
<h2>创建新帐户。</h2>
</hgroup>
@using (Html.BeginForm()) {
@Html.AntiForgeryToken()
@Html.ValidationSummary()
<fieldset>
<legend>注册表单</legend>
<ol>
<li>
@Html.LabelFor(m => m.UserName)
@Html.TextBoxFor(m => m.UserName)
</li>
<li>
@Html.LabelFor(m => m.Email)
@Html.TextBoxFor(m => m.Email)
</li>
<li>
@Html.LabelFor(m => m.Password)
@Html.PasswordFor(m => m.Password)
</li>
<li>
@Html.LabelFor(m => m.ConfirmPassword)
@Html.PasswordFor(m => m.ConfirmPassword)
</li>
<li>
@Html.LabelFor(m => m.OtherName)
@Html.TextBoxFor(m => m.OtherName)
</li>
</ol>
<input type="submit" value="注册" />
</fieldset>
}
@section Scripts {
@Scripts.Render("~/bundles/jqueryval")
<script src="~/Scripts/jQuery.validator.noteaualto.js"></script>
}
效果:
MVC验证05-自定义验证规则、验证2个属性值不等,古老的榕树,5-wow.com