MVC, RegularExpressionAttribute problem.
I am inheriting the RegularExpressionAttribute to create my own DataAnnotation for validating user input. It is not working for me.
I wish to only allow hyphens, spaces and upper/lowercase letters.
Regardless of what I input into the form on the MVC Web App, it shows the error message each time.
What am I doing wrong?
The custom DataAnnotation from the class is [NameValidation]
Code:
public class NameValidationAttribute : RegularExpressionAttribute
{
public NameValidationAttribute()
: base(@"/^[a-zA-Z \-]+$/")
{
ErrorMessage = "{0} can only consist of letters and spaces. Please correct your input.";
}
}
Re: MVC, RegularExpressionAttribute problem.
I even went to www.regexr.com and I put in the following regex. Says it is valid because it highlighted the text in the form on that site. But, when using it in my code above, I still get the error message on the view. What am I missing?
Re: MVC, RegularExpressionAttribute problem.
I do not believe this is the right expression. It does not validate a single character, it does validate underscores.
Code:
/([A-Za-z \-])\w+/g
This is the right expression, but the problem is how it is being assigned.
This does not work
Code:
public NameValidationAttribute() : base(@"/^[a-zA-Z \-]+$/")
This does work, notice how the forward slashes are omitted before the ^ and after the $.
Code:
public NameValidationAttribute() : base(@"^[A-Za-z \-]+$")
Just as a side note, you could assign the regular expression when declaring the attribute as below
Code:
public NameValidationAttribute(string Pattern)
: base(Pattern)
{
}
// Then specify the attribute on the property of the model
[NameValidation(@"^[A-Za-z \-]+$",ErrorMessage ="Not Valid Name")]
public string Name { get; set; }
To be honest, after all this work you are still only implementing the standard RegularExpressionAttribute and gaining nothing apart changing the name of the attribute.