[英]Reusing Validation Attributes in MVC5
我一直在進行有關驗證及其工作方式的大量研究。 我知道我們可以使用屬性,甚至可以創建自定義屬性,然后可以將其放到ViewModel上以驗證該數據。 盡管一切正常,但我發現自己正在多個ViewModel上重復使用相同的屬性組合。
例如,讓我們以一個“名稱”作為名稱,在項目X中使用一個名稱,無論它是電影名稱,書名,人名,姓氏等等。。。畢竟這是一個名稱,因此我傾向於使用90%的驗證屬性相同。 圖片,必填,最小長度3,最大長度50,僅字母,空格等。
現在,我得到一個變量,該變量具有5個以上的屬性。 這些是預先構建的屬性,由於它們已經為我編碼,因此我不希望再次編碼。 所以我的問題是這樣的:
我該如何創建CustomValidateName屬性,以對所有這些內容進行驗證,並根據錯誤內容提供不同的錯誤消息,同時又重用.NET框架中的某些內置屬性,因此我不會發明輪子。 最重要的是,只要我有一個Name變量,我現在就可以放一個屬性,而不是普通的5+。
使用可以為所有驗證創建自定義驗證
例如 :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
using System.Text.RegularExpressions;
namespace Custom_DataAnnotation_Attribute.Models
{
public class CustomEmailValidator : ValidationAttribute
{
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
if (value != null)
{
string email = value.ToString();
if (Regex.IsMatch(email, @"[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}", RegexOptions.IgnoreCase))
{
return ValidationResult.Success;
}
else
{
return new ValidationResult("Please Enter a Valid Email.");
}
}
else
{
return new ValidationResult("" + validationContext.DisplayName + " is required");
}
}
上面的方法為兩種必需的nd電子郵件類型生成驗證
您可以在此方法中使用If If Else或Switch來添加更多驗證,並還原自定義消息
型號:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
namespace Custom_DataAnnotation_Attribute.Models
{
public class EmployeeModel
{
public string Name { get; set; }
[CustomEmailValidator]
public string Email { get; set; }
public string Password { get; set; }
public string Mobile { get; set; }
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.