Validation

DNAide includes a number of components for improving validation:
  • ValidationError and ValidationException
  • ServerMessage WebControl - a simple webcontrol that renders a message into as a div with a "error, warning or normal css class". Also works with ValidationError to display a list of validation errors.
  • Simple jQuery client validation library

Pattern

Generally, I avoid using the built in .NET validation controls. As a personal preference I prefer the following pattern:
  • Define an object / controller. This typically maps to a database table and exposes methods for saving etc.
  • The object / controller ensures that all business rules are correct before saving.
  • The object / controller throws a ValidationException if any business rule has failed. The ValidationException contains a list of ValidationErrors.
  • Client displays and error message and a list of what rules have failed.
  • In addition, the client contains simple JavaScript validation to catch such things as required field, email address format etc.

e.g.

Object / Controller

public static class NewsController
{
	public static int Save(News objectToSave)
	{
		CheckBusinessRules(objectToSave);
		
		objectToSave.Save(auditUserName);
		return objectToSave.NewsId;
	}

	private static void CheckBusinessRules(News objectToValidate)
	{
		List<ValidationError> errors = new List<ValidationError>();
		objectToValidate.Headline = StringAide.StripXmlAndTrim(objectToValidate.Headline, 255);
		if (objectToValidate.Headline.Length < 1)
		{
			errors.Add(new ValidationError(string.Empty, string.Empty, 1, "Headline required"));
		}

		if (errors.Count > 0)
		{
			throw new ValidationException(errors);
		}
	}
}



ASPX codebehind

private void SaveRecord()
{
	try
	{
		News newsToSave = new News();
		newsToSave.Headline = txtHeadline.Text;
			
		int retval = newsToSave.Save(_currentRecord, "Admin", OriginalModifiedOn);
		Response.Redirect("record-updated.aspx");
	}
	catch (ValidationException ex)
	{
		// Write a bulletted list of server errors using the DNAide ServerMessage control
		FormServerMessage.SetMessage("Please correct the following", ex.ValidationErrors, ServerMessage.MessageDisplayType.Error);
	}	
}


ASPX

<html>
<head>
	// jQuery registered.
	// jQuery StringAide registered
	// jQuery ValidationAide registered
	
	<script type="text/javascript">
	$(document).ready(function() {
		$("#MyForm").validationAideEnable();		
	}
	</script>
</head>
<body>
<form runat="server" id="MyForm">
	<DNAide:ServerMessage ID="FormServerMessage" runat="server" />
	<asp:TextBox ID="txtHeadline" runat="server" CssClass="validator-required" title="Headline required" />

	// Submit buttons etc...
</form>
</body>


The jQuery Validation library includes a number of validation rules by default such as required, email address validation etc.

You can add your own validation rules e.g.

<script type="text/javascript">
$(document).ready(function() {
	var rules = $.validationAide.getDefaultValidationRules();
	rules.add('validator-custom', 'Value required - custom', function(v, elm, jQueryElm) {
		if (v == "") return false;
		return true;
	});
	$("#MyForm").validationAideEnable(rules);		
}
</script>


Then to use:

<asp:TextBox ID="txtHeadline" runat="server" CssClass="validator-custom" title="Headline required" />


You can chain rules by simply adding more css classes:

<asp:TextBox ID="txtHeadline" runat="server" CssClass="validator-required validator-custom" title="Headline required" />


You can enable and disable valiation on Html element events:

$("#SaveBtn").validationAideEnableOnClick("#MyForm");
$("#CancelBtn").validationAideDisableOnClick("#MyForm");



When enabling client validation, there are a number of configurable options:
  • hideErrorMessages: Hides the inline error message
  • showSpeed: How fast the error messages are faded in
  • summaryContainerId: The id of the html element to show error summary. Typically a DIV at the top of a form

$("#SaveBtn").validationAideEnableOnClick("#MyForm", {hideErrorMessages:true,showSpeed:'slow'});	

Last edited Mar 10, 2007 at 10:57 AM by stebrennan, version 3

Comments

que0x Aug 25, 2007 at 5:20 PM 
Hi,
How to apply validations on asp.net from with MasterPage ?