Cleaning up Custom Field Validator Code in an ASP.NET application.

Picking up a project that was already in full swing I was asked to fix up the shopping cart module for the site. The shopping cart need some validation added on 2 sections. The first section was mandatory, personal details, and   the second section was optional shipping details. The example has been simplified but the idea is the same.

The issues I wanted to address included

  • Remove inline scripts
  • Encapsulate javascript 
  • Added optional custom validation to an optional section of the page 

the asp.net markup that will need to be validated

li>label>Different Shipping Addresslabel>asp:CheckBox ID='chkHasNickName' runat='server' />li>

li>label>Shipping Addresslabel>

       asp:CustomValidator ID='cfvNickName' runat='server' Display='None' ErrorMessage='Please enter a nick name' ClientValidationFunction='CFVAPP.Validator.CV_NicknameEntered' />

       asp:TextBox ID='txtNickName' runat='server' />

li>

In the page load function we will need to make the id’s for the validation

protected override void OnLoad(EventArgs e) {

base.OnLoad( e );

       Page.ClientScript.RegisterExpandoAttribute( cfvNickName.ClientID, 'chkHasNickName', chkHasNickName.ClientID, false );

       Page.ClientScript.RegisterExpandoAttribute( cfvNickName.ClientID, 'txtNickName', txtNickName.ClientID, false );

}

We will now need to extend the javascript added before to complete some validation

CFVAPP.Validator = (function () {

return {

              CV_NicknameEntered: function (sender, arguments) {

 

                     var hasNickName = document.getElementById(sender.chkHasNickName);

                     var cvField = document.getElementById(sender.txtNickName);

 

                     if (cvField.value == '' && hasNickName.checked) {

                           arguments.IsValid = false;

                     }

                     return;

              }

       }

})();