Asp.Net MVC Data Annotations. How to get client side validation on 2 properties being equal

Posted by Mark on Stack Overflow See other posts from Stack Overflow or by Mark
Published on 2010-05-27T22:10:02Z Indexed on 2010/05/27 22:11 UTC
Read the original article Hit count: 596

Filed under:
|
|
|

How do you get client side validation on two properties such as the classic password confirm password scenario.

I'm using a metadata class based on EF mapping to my DB table, heres the code.

The commented out attributes on my class will get me server side validation but not client side.

[MetadataType(typeof(MemberMD))]
public partial class Member
{

    //[CustomValidation(typeof(MemberMD), "Verify", ErrorMessage = "The password and confirmation password did not match.")]
    //[PropertiesMustMatch("Password", "ConfirmPassword", ErrorMessage = "The password and confirmation password did not match.")]
    public class MemberMD
    {           

        [Required(ErrorMessage = "Name is required.")]
        [StringLength(50, ErrorMessage = "No more than 50 characters")]
        public object Name { get; set; }

        [Required(ErrorMessage = "Email is required.")]
        [StringLength(50, ErrorMessage = "No more than 50 characters.")]
        [RegularExpression(".+\\@.+\\..+", ErrorMessage = "Valid email required e.g. [email protected]")]
        public object Email { get; set; }


        [Required(ErrorMessage = "Password is required.")]
        [StringLength(30, ErrorMessage = "No more than 30 characters.")]
        [RegularExpression("[\\S]{6,}", ErrorMessage = "Must be at least 6 characters.")]
        public object Password { get; set; }

        [Required]
        public object ConfirmPassword { get; set; }

        [Range(0, 150), Required]
        public object Age { get; set; }


        [Required(ErrorMessage = "Postcode is required.")]
        [RegularExpression(@"^[a-zA-Z0-9 ]{1,10}$", ErrorMessage = "Postcode must be alphanumeric and no more than 10 characters in length")]
        public object Postcode { get; set; }

        [DisplayName("Security Question")]
        [Required]
        public object SecurityQuestion { get; set; }

        [DisplayName("Security Answer")]
        [Required]
        [StringLength(50, ErrorMessage = "No more than 50 characters.")]
        public object SecurityAnswer { get; set; }



        public static ValidationResult Verify(MemberMD t)
        {
            if (t.Password == t.ConfirmPassword)
                return ValidationResult.Success;
            else
                return new ValidationResult("");
        }
    }

Any help would be greatly appreciated, as I have only been doing this 5 months please try not to blow my mind.

© Stack Overflow or respective owner

Related posts about c#

Related posts about asp.net-mvc