Search code examples
c#javascriptasp.net-mvcdata-annotations

Using DataAnnotations to exclude a specific string when posting to an MVC controller


Hey guys I am using the following data-annotations to validate my model in a form post... this is working perfectly and I am getting the validation on the front end of my forms.

I want to add another data annotation that will not allow a given string example 'asdasd' I don't want that to be allowed in the YourName field I want them to still out put the same error messages as they are currently..

Any ideas?

public class Contact
{
    [Required(ErrorMessage = "Please enter your name.")]
    public string YourName { get; set; }

    [Required(ErrorMessage = "Please enter your email.")]
    [DataType(DataType.EmailAddress)]
    public string Email { get; set; }

    [Required(ErrorMessage = "Your missing a subject.")]       
    public string Subject { get; set; }

    [Required(ErrorMessage = "You haven't entered a message.")]
    public string Message { get; set; }
}

Solution

  • I would use a RegularExpresstionAttribute. The following regex should work. It tests that the value does not contain a particular string.

    [RegularExpression(@"^((?!asdasd).)*$", ErrorMessage = "'asdasd' is not allowed.")]