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", Error开发者_如何学GoMessage = "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. abc@xyz.com")]
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.
You just have to put this on your ConfirmPassword
attribute.
[Compare("Password", ErrorMessage = "Passwords don't match.")]
[Required]
public object ConfirmPassword { get; set; }
It means that it is going to compare your ConfirmPassword
attribute with your Password
attribute.
1) The ConfirmPassword object should be set up similar to the Password. 2) the ConfirmPassword object should have another property OriginalPasswordInputControl which is the "Password" and 3) in your utility class or whereever your handling validation will check :
//Probably in a function - something like Protected bool ValidateControl()
if (elementToValidate.Password != OriginalPasswordInputControl.Password)
{
return false;
}
else
{
return true;
}
You could use the CompareTo attribute. As answers to that question pointed out, they are not terribly flexible, but would address your needs.
精彩评论