The following is an example of how to validate a field using the asp:customvalidator control. I am going to be validating a textbox to ensure that its entry is alphanumeric without any spaces.
This is the field to be validated...
<asp:TextBox id='PersonId' runat='server' />
Here is the asp:CustomValidator on the aspx page.
<asp:CustomValidator id='PersonIdCustomValidator' runat='server'
Display='Dynamic'
ControlToValidate='PersonId'
EnableClientScript='true'
ClientValidationFunction='ValidatePersonId'
OnServerValidate='ValidatePersonId'
Text='* PersonId must be alphanumeric without any spaces' />
Javascript implementation of the client-side validation.
function ValidatePersonId(source, args)
{
var re = new RegExp("^\\w*$");
args.IsValid = (window.event.srcElement.value.match(re));
}
C# codebehind implementation of the server-side validation.
protected void ValidatePersonId(object source, ServerValidateEventArgs args)
{
bool valid = false;
Regex re = new Regex("^\\w*$");
if (args.Value.Length == 0)
{
valid = true;
}
else if (re.IsMatch(args.Value))
{
valid = true;
}
if (valid)
{
args.IsValid = true;
}
else
{
args.IsValid = false;
}
}