title: Server Side Validation with .NET WebAPI
body: <p>For arguments sake let's say that I am on the Create View.  If I left all of the textboxes empty and hit submit, I would get returned the same form but with validation messages under each textbox that was required, and that was done by client side validation.  Now, when that happens, each textbox is decorated with a class name called <code>input-validation-error</code>, and if I style that I can make the box turn red to make it stand out more to the user.</p>
  
  <p>But now, let's say that one of the textboxes requires an email address.  Email addresses are unique so in my webapi controller I have this:</p>
  
  <pre><code>// POST: api/ControllerName
  [ResponseType(typeof(TestObject))]
  public IHttpActionResult PostTestObject(TestObject testObject)
  {
      if (!ModelState.IsValid)
      {
          return BadRequest(ModelState);
      }
  
      if (
          db.TestObjects.Any(
              x =&gt;
                  x.Email.Equals(testObject.Email, StringComparison.CurrentCultureIgnoreCase) &amp;&amp;
                  x.ID != testObject.ID))
      {
              ModelState.AddModelError("Email", "This Email Already Exists!");
              return BadRequest(ModelState);
      }
  
      db.TestObjects.Add(testObject);
      db.SaveChanges();
  
      return CreatedAtRoute("DefaultApi", new { id = testObject.ID }, testObject);
  }
  </code></pre>
  
  <p>In my Create View I have this to display that exception message:</p>
  
  <pre><code>.error(function (jqXHR, textStatus, errorThrown) {
      var status = capitalizeFirstLetter(textStatus);
      var error = $.parseJSON(jqXHR.responseText);
      toastr.error(status + " - " + error.exceptionMessage);
   });
  </code></pre>
  
  <p>This displays the exception message in a toastr notification.  But it doesn't give the email textbox a class name of <code>input-validation-error</code>, and I would like it to so that it will display the textbox in red.</p>
  
  <p>Is there a way in WebApi controller methods to return something that will add that class to that textbox?  I know in regular .Net controllers I could do</p>
  
  <pre><code>ModelState.AddModelError("Email", "This email already exists!")
  return View(testObject);
  </code></pre>
  
  <p>That would return the view with that textbox having the css class name.</p>
  
  <p>Any help is appreciated.</p>
  
  <p>Based on Nkosi's answer below:</p>
  
  <p>When I <code>console.log(JSON.stringify(error));</code></p>
  
  <p>The response is this:</p>
  
  <pre><code>{"$id":"1","message":"The request is invalid.","modelState":
  {"$id":"2","email":["This Email Already Exists!"]}} 
  </code></pre>
  
  <p>Okay, so I have changed the formatting to fit the JSON response, and I have also changed the <code>var id</code> line to <code>var id = "#" + key.replace('$', '');</code></p>
  
  <p>Now I am receiving an error on <code>valmsg.text(value.join());</code> saying <code>Object doesn't support property or method 'join'</code>.. so I consoled the value and it is <code>2</code>.. not <code>"This Email Already Exists!"</code></p>
  
  <p><strong>UPDATE</strong></p>
  
  <pre><code>.error(function (jqXHR, textStatus, errorThrown) {
      var error = jqXHR.responseJSON;
      console.log(JSON.stringify(error));
      var message = error.message;
      var modelState = error.modelState;
  
      $.each(modelState,
          function (key, value) {
              var id = "#" + key.replace('$', '');
              var input = $(id);
              console.log(id); // result is #id
              if (input) { // if element exists
                  input.addClass('input-validation-error');
              }
              //get validation message
              var valmsg = $("[data-valmsg-for='" + key + "']");
              if (valmsg) {
                  valmsg.text(value.join()); // Object doesn't support property or method 'join'
                  valmsg.removeClass("field-validation-valid");
                  valmsg.addClass("field-validation-error");
              }
  </code></pre>