Friday, October 31, 2008

Custom Validators

Among other validators, asp.net has a custom validator, allowing programmer to assign a client validation function (javascript) and backend validation method(c#).

Here is my code for CreateUserWizard control:


<asp:CustomValidator ID="vldEmailCustom" runat="server" OnServerValidate="ValidateEmail"
ClientValidationFunction="onClientValidateEmail" ControlToValidate="Email"
ValidationGroup="wzdCreateUser" Width="1"
ErrorMessage="Invalid email." ToolTip="Invalid email.">*</asp:CustomValidator>


// client javascript handler
function onClientValidateEmail(sender, args)
{
var email = args.Value;
var regex = /^[a-z0-9\._-]+@([a-z0-9_-]+\.)+[a-z]{2,6}$/i;
if(regex.test(email)){
args.IsValid = true;
}
else{
args.IsValid = false;
}
}



// backend handler
protected void ValidateEmail(object sender, ServerValidateEventArgs args)
{
args.IsValid = Validation.ValidateEmail(args.Value, EmailValidationType.Lenient);
}


Even a clientside validation is facilitated, serverside validation is strongly suggested to prevent intention of accessing backend bypassing the client validation.

Page.IsValid couldn't be accessed within Page_Load event handler, because at the point of time the page is now validated. However, you can cal Page.Validate() before check IsValid property. Accessing IsValid property seems cause a call to Page.Validate() method.


A control's CauseValidation attribute indicates whether to call Page.Validation automatically when the control makes a postback. In the handler, the suggested way is that check IsValid property before processing associated logic.

When using Validators, make sure the validation scope is set properly.

No comments: