gpt4 book ai didi

c# - 如何创建自定义验证属性?

转载 作者:行者123 更新时间:2023-12-04 16:31:40 25 4
gpt4 key购买 nike

我正在尝试创建自定义验证属性。

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);
}

}

用法:

客户元数据.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;
}

链接:

How to: Customize Data Field Validation in the Data Model Using Custom Attributes

关于c# - 如何创建自定义验证属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23780943/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com