本文體驗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>
}
效果: