MVC数据注释和自定义验证属性

时间:2016-01-09 19:29:57

标签: c# asp.net-mvc data-annotations

我在模型中有一个字段,内置数据注释和自定义验证属性似乎无法正常工作。看起来执行顺序存在问题。

[Required]
[Display(Name = "UserName")]        
[RegularExpression(@"^[^\s\,]*$", ErrorMessage = "Username Cannot must not contain any spaces or commas")]
[UnqiueUserName]
public string UserName { get; set; }


public class UnqiueUserName : ValidationAttribute
{
    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        if (value != null && Membership.GetUser(value.ToString()) != null)
        {
            return new ValidationResult
                    (string.Format("UserName Already Exist"));
        }

        return ValidationResult.Success;
    }
}

如果我输入用户名用户,123 首先执行自定义验证属性,并使异常发生。

The parameter "username" must not contain a comma

但如果我输入用户123 ,则此次首先执行内置数据注释正则表达式。

我想在内置版之后使用自定义验证属性。请建议

0 个答案:

没有答案