使用DataAnnotation进行电话验证

本文关键字:电话 验证 DataAnnotation 使用 | 更新日期: 2023-09-27 18:00:15

我想验证我的电话号码,对于每种无效情况,我都希望收到另一条错误消息:

所以,我的验证规则:

  1. 只有9位->错误消息="错误消息1"
  2. 数字不能是相同的数字,例如222222222>错误message="错误消息2"
  3. 不能是类似于'123456789'>错误消息="错误消息3"的字符串
  4. 无法从0>错误消息="错误消息4"开始

MyPhoneAttribute:

[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field)]
public class MyPhoneAttribute : RegularExpressionAttribute
{
    private const string myRegex = @"^([0-9]{9}){0,1}$";
    public MyPhoneAttribute () : base(myRegex )
    {
        ErrorMessage = "default error message";
    }
    public override bool IsValid(object value)
    {
        if (string.IsNullOrEmpty(value as string))
            return true;
        if (value.ToString() == "123456789")
        {
            return false;
        }
        if (Regex.IsMatch(value.ToString(), @"^([0-9])'1*$"))
        {
            return false;
        }
        return Regex.IsMatch(value.ToString(), @"^([0-9])'1*$");
    }
}

使用DataAnnotation进行电话验证

这不是一个完美的解决方案,我稍后会对其进行改进,但现在您可以尝试以下操作(注意,这里我使用了ValidationAttribute,但没有使用RegularExpressionAttribute作为基类):

[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field)]
public class MyPhoneAttribute : ValidationAttribute
{
    private const string nineDigitsPattern = @"^([0-9]{9}){0,1}$";
    private const string sameNumberPattern = @"('w)'1{9,}"; // here 9 the same numbers
    public override bool IsValid(object value)
    {
        var validationNumber = (string)value;
        if (string.IsNullOrEmpty(validationNumber))
            return true;
        // case 4
        if (validationNumber.StartsWith("0"))
        {
            ErrorMessage = "error message 4";
            return false;
        }
        // case 3       
        if (validationNumber.Equals("123456789"))
        {
            ErrorMessage = "error message 3";
            return false;
        }
        // case 2
        if (Regex.IsMatch(validationNumber, sameNumberPattern)) {
            ErrorMessage = "error message 2";
            return false;
        }
        // case 1
        if (Regex.IsMatch(validationNumber, nineDigitsPattern))
        {
            ErrorMessage = "error message 1";
            return false;
        }
        return true;
    }
 }