这几天在捣鼓自定义验证属性,网上搜罗很多都是在MVC中使用的。
我要的效果是后台属性添加上自定义属性标签,然后业务处理中用到这个属性时会触发自定义属性的验证。
自定属性代码写好了,可测试中就是不触发这个自定义属性的方法。请了解的大侠帮帮忙。
自定义验证属性代码如下:
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false)] public sealed class CustomAttribute : ValidationAttribute { // Internal field to hold the mask value. readonly string _mask; public string Mask { get { return _mask; } } public CustomAttribute(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); } }
实体类如下:
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.DynamicData; using System.ComponentModel.DataAnnotations; /// <summary> /// Customer 的摘要说明 /// </summary> [MetadataType(typeof(CustomerMetadata))] public partial class Customer { [Custom("999-999-9999", ErrorMessage = "{0} value does not match the mask {1}.")] public string Phone; }
调用方式:
protected void btn_Click(object sender, EventArgs e) { try { Customer c = new Customer(); c.Phone = txt.Text.Trim(); } catch (Exception ex) { } }
我想实现的是输入的信息与验证信息不符合时,给出错误信息。