Search code examples
c#asp.net-mvcvalidationasp.net-mvc-viewmodel

How to make a something required AND use a regular expression attribute?


I have a viewmodel that works fine EXCEPT if the person enters nothing and hits submit, then i get a db error because the column doesn't except nulls.

I am doing

 if (ModelState.IsValid)

How can I make this Email field use a RegularExpression AND a required attribute at the same time?

public class RegistrationViewModel
{
    [RegularExpression(@"^......$", ErrorMessageType = ..., ErrorMessageResourceName = ...]
    public string Email {get;set;}

    ...
}

Solution

  • Just use the RequiredAttribute.

    [Required(AllowEmptyStrings = false)]
    

    Now, if there isn't a value it will fail and if there is one the RegularExpressionAttribute will validate it.