Domanda

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;}

    ...
}
È stato utile?

Soluzione

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.

Altri suggerimenti

You can add many validation attributes like this :

[Required(ErrorMessage = "Email address is mandatory")]
[RegularExpression(@"^......$", ErrorMessageType = ..., ErrorMessageResourceName = ...]
public string Email {get;set;}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top