2

重複するユーザー名と電子メールのカスタム検証を作成したいと考えています。モデルはそうです:

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" );
    }
}

すべての検証は機能しますが、私のカスタム検証 - ValidateDuplicateUsernameValidateDuplicateEmailは機能しません。ここで何が問題なのですか?

4

1 に答える 1

1

カスタム属性を実装する必要がありますIClientValidateable

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

于 2012-08-31T06:36:03.417 に答える