Uncovering Silent Validation

ASP.Net validation is very useful and allows developers to ensure data is correct before it gets sent to a data store. Validation can run either on the client side or on the server side and each have their advantages and disadvantages.
MVC and Webforms handle validation slightly differently and I won't go into those differences in this article. Instead, I would like to explain some best practices and suggestions for you when implementing ASP.Net validation.

Bind Validation To HTML Elements

To implement validation, you first add an HTML element to a page, then a validation element points to that HTML element. In MVC, you would write something like this for a model field called Name.
  1. <div class="editor-field col-md-10">  
  2.     <div class="col-md-6">  
  3.         @Html.TextBoxFor(model => model.Name, new { @class = "form-control" })  
  4.     </div>  
  5.     <div class="col-md-6">  
  6.         @Html.ValidationMessageFor(model => model.Name)  
  7.     </div>  
  8. </div>  
In Webforms, it would be like this.
  1. <asp:DropDownList ID="Name" runat="server" AutoPostBack="true" FriendlyName="Option:"  
  2. AddBlankRowToList="false" DisplayBlankRowText="False" CausesValidation="true">  
  3. <asp:ListItem Text="Option 1" Value="1"></asp:ListItem>  
  4. <asp:ListItem Selected="True" Text="Option 2" Value="2"></asp:ListItem>  
  5. </asp:DropDownList>  
  6. <asp:CustomValidator ID="valCheck" ControlToValidate="Name" Display="Static" runat="server" ForeColor="red"  
  7. ErrorMessage="Validation Error Message" SetFocusOnError="True"  
  8. OnServerValidate="CheckForAccess" />  
This results in HTML elements with attributes that will allow the client-side validation framework to execute.

Check For Validation Errors On Postback

Whereas validation should run on the client-side before the form is submitted to the server, it is still a good practice to check for errors on the server. There are a number of reasons for this, but the main reason should be that the client is an unknown quantity. There are different browsers, JavaScript can be disabled, developer tools allow people to modify HTML and hence could result in unexpected data being posted. So, check your validation before you begin processing your form data on the server. And it's as simple as wrapping your server-side logic in a single code block.
  1. [HttpPost]  
  2. [ValidateAntiForgeryToken]  
  3. public ActionResult Edit(ViewModel model)  
  4. {  
  5.     if (ModelState.IsValid())  
  6.     {  
  7.         // your code to process the form  
  8.     }   
  9.     else  
  10.     {  
  11.         ModelState.AddModelError(String.Empty, "Meaningful Error message);  
  12.         return View(model);  
  13.     }  
  14.     return RedirectToAction("Index");  
  15. }  
  1. protected void Page_Load(object sender, EventArgs e)  
  2. {  
  3.     if (IsPostback)  
  4.     {  
  5.         if (!IsValid)  
  6.         {  
  7.             // validation failed. Do something  
  8.             return;  
  9.         }  
  11.         // do your form processing here because validation is valid  
  12.     }   
  13.     else   
  14.     {  
  15.         // non-postback  
  16.     }  
  17. }  

Do Something Useful With Your Validation Errors

If you find that validation errors are getting through to your server, you need to capture them and show them to the user. A quick way that I have found to do this is with a loop using the validator collection and look for errors. There are a number of things you can do like add the error messages to the Validation Summary box at the top of your form, write to an audit log or make them appear in a dialog box.
  1. foreach (IValidator aValidator in this.Validators)  
  2. {  
  3.     if (!aValidator.IsValid)  
  4.     {  
  5.         Response.Write("<br />" + aValidator.ErrorMessage);  
  6.     }  
  7. }  
Validation is a critical part of form submission and should be used to it's full potential.
Until next time …
For more articles like this one, see Steven's blog at http://www.webdesignwith.net/ 

Up Next
    Ebook Download
    View all
    View all