Asp.Net Mvc how to Conditional Validation

时间:2015-11-29 08:58:59

标签: c# asp.net-mvc-5 asp.net-mvc-validation validationattribute

I'm trying to build a demo application for gain Asp.Net Mvc 5 development experience. In these days i'm trying to build a site settings.

I've a model named Settings. And there are properties like below.

    public int PasswordRequiredLength { get; set; }
    public bool PasswordRequireNonLetterOrDigit { get; set; }
    public bool PasswordRequireDigit { get; set; }
    public bool PasswordRequireLowercase { get; set; }
    public bool PasswordRequireUppercase { get; set; }
    public bool UseAlphaNumericCharacters {get; set; }          

In ApplicationUserManager i made thse modifications.

        // Configure validation logic for passwords
        manager.PasswordValidator = new PasswordValidator
        {
            RequiredLength = CacheHelper.Settings.PasswordRequiredLength > 0 ? CacheHelper.Settings.PasswordRequiredLength : 8,
            RequireNonLetterOrDigit = CacheHelper.Settings.PasswordRequireNonLetterOrDigit ? true : false,
            RequireDigit = CacheHelper.Settings.PasswordRequireDigit ? true : false,
            RequireLowercase = CacheHelper.Settings.PasswordRequireLowercase ? true : false,
            RequireUppercase = CacheHelper.Settings.PasswordRequireUppercase ? true : false
        };

So, password validation will be specified at run time. So far so good. The application a bit more flexible. But! What about RegisterViewModel.

There are properties like below

    [StringLength(20, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 5)]
    [RegularExpression("^([a-zA-Z0-9]{5,20})$", ErrorMessage = "The {0} must contain only alphanumeric characters")]
    [Display(ResourceType = typeof (Resources.Translations), Name = "Username")]
    public string UserName { get; set; }

    [Required]
    [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
    [DataType(DataType.Password)]
    [Display(Name = "Password")]
    public string Password { get; set; }

How can i validate password minimum, length? Or AlphaNumeric characters if PasswordRequireNonLetterOrDigit false? Same thing on UserName. It depends UseAlphaNumericCharacters

Thank you.

0 个答案:

没有答案