复制的自定义验证不起作用

时间:2012-08-31 06:19:32

标签: asp.net-mvc-3 validation custom-attributes model-validation

我想为重复的用户名和电子邮件创建自定义验证。模型是这样的:

public class RegisterModel
{
    [Required( ErrorMessage = "Username is empty" )]
    [StringLength( 100, ErrorMessage = "Minimum 5 symbol", MinimumLength = 5 )]
    [CustomValidation( typeof( RegisterModel ), "ValidateDuplicateUsername" )]
    [RegularExpression( @"^[a-zA-Z0-9]+$", ErrorMessage = "Username invalid" )]
    public string UserName { get; set; }

    [RegularExpression( @"^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$", ErrorMessage = "Enter valid e-mail" )]
    [Required( ErrorMessage = "E-mail is empty" )]
    [DataType( DataType.EmailAddress )]
    [CustomValidation( typeof( RegisterModel ), "ValidateDuplicateEmail" )]
    public string Email { get; set; }

    [Required( ErrorMessage = "Password is empty" )]
    [StringLength( 100, ErrorMessage = "Minimum 6 symbol", MinimumLength = 6 )]
    [DataType( DataType.Password )]
    public string Password { get; set; }

    [DataType( DataType.Password )]
    [Compare( "Password", ErrorMessage = "Password not same" )]
    public string ConfirmPassword { get; set; }

    public static ValidationResult ValidateDuplicateUsername( string username )
    {
        if ( username != null )
        {
            bool isValid = true;
            MembershipUserCollection users = Membership.GetAllUsers();
            foreach ( MembershipUser item in users )
            {
                if ( item.UserName.ToUpper().Equals( username.ToUpper() ) )
                {
                    isValid = false;
                }
            }

            if ( isValid )
            {
                return ValidationResult.Success;
            }
            else
            {
                return new ValidationResult( "Username exists" );
            }
        }
        else return new ValidationResult( "Minimum 5 symbol" );
    }

    public static ValidationResult ValidateDuplicateEmail( string email )
    {
        if ( email != null )
        {
            bool isValid = true;
            MembershipUserCollection users = Membership.GetAllUsers();
            foreach ( MembershipUser item in users )
            {
                if ( item.Email.ToUpper().Equals( email.ToUpper() ) )
                {
                    isValid = false;
                }
            }

            if ( isValid )
            {
                return ValidationResult.Success;
            }
            else
            {
                return new ValidationResult( "Username exists with this email" );
            }
        }
        else return new ValidationResult( "Enter valid e-mail" );
    }
}

所有验证都有效,但我的自定义验证 - ValidateDuplicateUsername ValidateDuplicateEmail 不起作用。这有什么不对?

1 个答案:

答案 0 :(得分:1)

您需要使自定义属性实现IClientValidateable

示例:http://www.codeproject.com/Articles/275056/Custom-Client-Side-Validation-in-ASP-NET-MVC3