Search code examples
asp.net-mvc-2data-annotations

Understanding client and server side validation using data annotations


I'm using MVC 2. I have a question regarding client and server side validation. Lets say I have a class, and it has 3 properties as such:

[Required(ErrorMessage = "Required")]
public object Property1 { get; set; }

[Required(ErrorMessage = "Required")]
public object Property2 { get; set; }

[Required(ErrorMessage = "Required")]
public object Property3 { get; set; }

On my view I ONLY have Property1 and Property 2 and make them textboxes. I did not add Property3 to the view (but it is marked as required as above). If I don't type anything into the textboxes then the client side validation will fail. If I insert text into the textboxes, will client side pass even though Property3 was not set with a value? Will it then fail on the server side?

The issue that I am having is on the server side after I clicked the submit button. Here is my code for my Create action:

public ActionResult CreateApplication(Application application)
{
   try
   {
      application.ApplicationStateID = 1;
      application.SubmitterEmployeeNumber = "123456";

      if (ModelState.IsValid)
      {
         // Code here
      }
   }
   catch
   {
   }
}

ApplicationStateID and SubmitterEmployeeNumber is not set on client side (they are both marked as required), so I set it here. After I set them, why would validation still fail on the server side?


Solution

  • Client side validation will pass because there's no corresponding input element to validate, server side validation will fail because you enforce a field to be required and this field value is not posted to the server. You could read this blog post to understand how model validation works and the differences between Input Validation vs Model Validation.