Reputation: 4133
I'm a nub in MVC.I've a Model:
public class Usuarios
{
[Required(ErrorMessage = "**TxtOPID is required")]
public string TxtOpID
{
get { return this.txt_opId; }
set { this.txt_opId = value; }
}
[Required(ErrorMessage="**Password is required")]
public string TxtPassword
{
get { return this.txt_password; }
set { this.txt_password = value; }
}
[Required(ErrorMessage="**Email is required")]
[RegularExpression("^[a-z0-9_\\+-]+(\\.[a-z0-9_\\+-]+)*@[a-z0-9-]+(\\.[a-z0-9-]+)*\\.([a-z]{2,4})$",ErrorMessage="**Invalid email")]
public string TxtEmail
{
get { return this.txt_email; }
set { this.txt_email = value; }
}
}
This is DataAnnotations and works fine when i try to check if all properties are valid with ModelState.IsValid propertie.
The problem is when i dont want to check ALL properties.i.e: If i want to check only TxtOPID and TxtSenha propertie,like in a Login form,where only OPID and Password are required.
How can i exclude Email propertie validation,in a specific Action in a controller?
I tried:
public ActionResult SignIn([Bind(Exclude="TxtEmail")]Usuarios usuario)
{
[...]
}
But it doesn't work,its always INVALID cause,TxtEmail is not required for that specific form.
Any ideias?
Upvotes: 1
Views: 1922
Reputation: 47387
Don't put all of your validation in a single class. Build a class for Login
, and another one for Contact
, etc.
Basically each model will have DataAnnotations to validate that model.. even if you have 30 different ones. You can always create a Base Class and put common properties in there and simply inherit from it.
In my situation I have a login form and the Class (using DataAnnotations) validates "UserName" and "Password". I also have an "Events" form that requires the event name, date, time, etc. So I have another Class for validating events.
Upvotes: 3