如何创建自定义验证属性
本文关键字:自定义 验证 属性 创建 何创建 | 更新日期: 2023-09-27 18:04:19
我正在尝试创建一个自定义验证属性。
public class PhoneValidator : ValidationAttribute
{
public override bool IsValid(object value)
{
return new RegularExpressionAttribute(@"^[+0]'d+").IsValid(Convert.ToString(value).Trim());
}
}
我用这个来使用
[PhoneValidator]
public string PhoneNumber { get; private set; }
我从一个网站上复制的,理论上这应该是可行的。
来自MSDN的示例:
PhoneMaskAttribute cs:
using System;
using System.Globalization;
using System.ComponentModel.DataAnnotations;
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false)]
sealed public class PhoneMaskAttribute : ValidationAttribute
{
// Internal field to hold the mask value.
readonly string _mask;
public string Mask
{
get { return _mask; }
}
public PhoneMaskAttribute(string mask)
{
_mask = mask;
}
public override bool IsValid(object value)
{
var phoneNumber = (String)value;
bool result = true;
if (this.Mask != null)
{
result = MatchesMask(this.Mask, phoneNumber);
}
return result;
}
// Checks if the entered phone number matches the mask.
internal bool MatchesMask(string mask, string phoneNumber)
{
if (mask.Length != phoneNumber.Trim().Length)
{
// Length mismatch.
return false;
}
for (int i = 0; i < mask.Length; i++)
{
if (mask[i] == 'd' && char.IsDigit(phoneNumber[i]) == false)
{
// Digit expected at this position.
return false;
}
if (mask[i] == '-' && phoneNumber[i] != '-')
{
// Spacing character expected at this position.
return false;
}
}
return true;
}
public override string FormatErrorMessage(string name)
{
return String.Format(CultureInfo.CurrentCulture,
ErrorMessageString, name, this.Mask);
}
}
用法:
CustomerMetadata.cs:
using System.Web.DynamicData;
using System.ComponentModel.DataAnnotations;
[MetadataType(typeof(CustomerMetadata))]
public partial class Customer
{
}
public class CustomerMetadata
{
[PhoneMask("999-999-9999",
ErrorMessage = "{0} value does not match the mask {1}.")]
public object Phone;
}
链接:
如何使用自定义属性在数据模型中自定义数据字段验证
1-创建class
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
public class MobileValidationAttribute : ValidationAttribute
{
public MobileValidationAttribute(string errorMessage)
{
ErrorMessage = errorMessage;
}
public override bool IsValid(object value)
{
if (value == null) return false;
return value.ToString().Length == 13;
}
}
创建model
public class UserModel
{
[Display(Name ="Phone Number")]
[MobileValidation("{0} is invalid")]
[Required(AllowEmptyStrings =false,ErrorMessage ="{0} is required")]
public string PhoneNumber { get; set; }
}
在视图中使用此代码
@model TestAttribute.Models.UserModel
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
<div>
<form method="post" action="/Home/Index">
@Html.LabelFor(a=>a.PhoneNumber)
@Html.TextBoxFor(a=>a.PhoneNumber)
@Html.ValidationMessageFor(a=>a.PhoneNumber)
<br />
<br />
<button type="submit">Add</button>
</form>
</div>
</body>
</html>
4-和Controller
public class HomeController : Controller
{
public ActionResult Index()
{
return View(new UserModel());
}
[HttpPost]
public ActionResult Index(UserModel model)
{
if (ModelState.IsValid)
{
return Content("Ok");
}
return View(model);
}
}