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 pitfalls.
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 which points to that HTML element.
In MVC, you would write something like this for a model field called Name.
<div class="editor-field col-md-10">
<div class="col-md-6">
@Html.TextBoxFor(model => model.Name, new { @class = "form-control" })
</div>
<div class="col-md-6">
@Html.ValidationMessageFor(model => model.Name)
</div>
</div>
In Webforms, it would be like this.
<asp:DropDownList ID="Name" runat="server" AutoPostBack="true" FriendlyName="Option:"
AddBlankRowToList="false" DisplayBlankRowText="False" CausesValidation="true">
<asp:ListItem Text="Option 1" Value="1"></asp:ListItem>
<asp:ListItem Selected="True" Text="Option 2" Value="2"></asp:ListItem>
</asp:DropDownList>
<asp:CustomValidator ID="valCheck" ControlToValidate="Name" Display="Static" runat="server" ForeColor="red"
ErrorMessage="Validation Error Message" SetFocusOnError="True"
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
While 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.
MVC
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(ViewModel model)
{
if (ModelState.IsValid())
{
// your code to process the form
}
else
{
ModelState.AddModelError(String.Empty, "Meaningful Error message);
return View(model);
}
return RedirectToAction("Index");
}
Webforms
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostback)
{
if (!IsValid)
{
// validation failed. Do something
return;
}
// do your form processing here because validation is valid
}
else
{
// non-postback
}
}
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 loop through the validator collection and look for errors. There are a number of things you could 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.
foreach (IValidator aValidator in this.Validators)
{
if (!aValidator.IsValid)
{
Response.Write("<br>" + aValidator.ErrorMessage);
}
}
Validation is a critical part of form submission and should be used to it's full potential.
Til next time ...