Owen
Owen

Reputation: 4417

MVC4 Model Validation Server Side in API Controller

I've got an admin view and on part of the view are a few text boxes for registering new users. I'm using a RegisterModel class as part of my view model so that I get all the client side validation, but I'm stopping the form submit using jquery, confirming validation client side using jquery, then sending the model to an API controller with ajax.

Here's a stripped down version of my RegisterModel.

[Required(ErrorMessage = "User Name Required")]
public string UserName { get; set; }
[Required(ErrorMessage = "Email Required")]
[RegularExpression("REGEX", ErrorMessage = "Invalid Email")]
public string Email { get; set; }
[Required(ErrorMessage = "Password Required")]
public string Password { get; set; }
[Compare("Password", ErrorMessage = "Passwords do not match")]
public string ConfirmPassword { get; set; }

Here's the start of my Register method in my API controller:

[HttpPost]
public void Register (RegisterModel newUser)
{
   // Validate User

}

How can I take advantage of all my data annotations and validate my model in my API controller? Something like newUser.Validate();

Upvotes: 1

Views: 3362

Answers (2)

glautrou
glautrou

Reputation: 3198

Ok, so if you want to validate server-side you have to do this:

[HttpPost]
public void Register (RegisterModel newUser)
{
   if (ModelState.IsValid)
   {
      // Model valid, can save
      /* Save and redirect */
   }
   else
   {
      // Model not valid returned by ASP.Net and Entity Framework
      return View(newUser); // return view including current model with errors
   }

}

Note:

When you call ModelState.IsValid that will force your model to be validated. The validation of your model means that ASP.Net will validate your .Net data annotations, Entity Framework will validates your Entity Framework data annotations and Entity Framework will validate your custom business logic.

ModelState.IsValid is the property you can trust for validating your data just before saving, it will handle all verification not made client-side (because not supported or JavaScript disabled).

Upvotes: 4

Sharun
Sharun

Reputation: 3082

You can use

if (ModelState.IsValid) {

inside the action to validate the model.

ie;

[HttpPost]
public void Register (RegisterModel newUser)
{
     if (ModelState.IsValid) {
     //process form data

      }

}

Upvotes: 4

Related Questions