asp.net mvc中的自定义DataAnnotation不起作用

时间:2014-01-17 22:01:37

标签: asp.net asp.net-mvc

[Required]
[ValidatePasswordLength]

[DataType(DataType.Password)] 
[Display(Name = "Password")]
[Minimumthreenumbers]
public string Password { get; set; }

public class MinimumthreenumbersAttribute : ValidationAttribute 
{

    private const string _defaultErrorMessage = "There should be minimum three letters in the string";

    private string Otherpassword;

    public MinimumthreenumbersAttribute() : base(_defaultErrorMessage)
    {


    }

    public override bool IsValid(object value)
    {
        string i = value.ToString();
        string jobId = i;
        int digitsCount = 0;
        foreach (char c in jobId)
        {
            if (Char.IsDigit(c))
                digitsCount++;
        }

        if (digitsCount > 3)
        {

            return true;
        }


        else
        {

            return false;
        }


    }
}

以上是自定义属性实现类。The above code actually has to validate the password to check for minimum 3 numbers.If the user entered password has less than 3 digits it should throw an error。这是要求。但是没有按预期工作。关于如何使上述代码工作的任何想法?我已经尝试了一段时间但仍然没有用。

2 个答案:

答案 0 :(得分:2)

不确定这是否足以使您的代码“正常”,但至少这会简化您的代码。

public class MinimumthreenumbersAttribute : ValidationAttribute 
{
   public MinimumthreenumbersAttribute() : base("There should be minimum three letters in the string")
   {
   }

   public override bool IsValid(object value)
   {
       return value != null && 
              value.ToString()
                   .Where(Char.IsDigit)
                   .Count() >=3
   }
}

答案 1 :(得分:0)

您可以使用RegularExpressionAttribute来确保有三个数字:

[RegularExpression(@".*\d.*\d.*\d.*")]
public string Password { get; set; }