0

I have a regular expression data annotation:

[StringLength(100)]
[Display(Description = "Password")]
[RegularExpression(@^((?=.*[a-z])(?=.*[A-Z])(?=.*\d)).+$)], ErrorMessage = " must include at least one upper case letter,one lower case letter and one numeric digit")]
public string Password { get; set; }

How can I display an Error Message based on the reason the validation failed?

If the password is 12345678 then tell the user he didn't include at least 1 upper case and 1 lower case.

If the password is abcdefgH then the Error message will be:"must insert at least 1 digit".

2 Answers 2

1

One way this could be done is to create your own regex validation attributes. You can extend the RegularExpressionAttribute and thereby seperate the different parts of your regex:

public class UpperAndLowerCaseAttribute : RegularExpressionAttribute
{
    public UpperAndLowerCaseAttribute()
        : base("**YOUR REGEX HERE**")
    {
    }
}

You can then use it like so:

[UpperAndLowerCaseAttribute, ErrorMessage = "ERRORMESSAGE"]
public string Password { get; set; }
Sign up to request clarification or add additional context in comments.

3 Comments

It doesn't work in the view using unobtrusive validation, but i believe it should work for server side validation
My unobtrusive validation works except this one. That doesn't work also after the submit.
I had to add in my global.asax this: DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(UpperAndLowerCaseAttribute), typeof(RegularExpressionAttributeAdapter));
0

My custom class:

public class UpperAndLowerCaseAttribute : RegularExpressionAttribute
{
    public UpperAndLowerCaseAttribute()
        : base("**YOUR REGEX HERE**")
    {
    }
}

How to use it:

[UpperAndLowerCaseAttribute, ErrorMessage = "ERRORMESSAGE"]
public string Password { get; set; }

Add this to the global.asax to get recognized in client side:

DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(UpperAndLowerCaseAt‌​tribute), typeof(RegularExpressionAttributeAdapter));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.