views:

169

answers:

2

what goes in the code behind for the Server Validate event of a Custom Validator, which is attempting to validate a set of 2 radiobuttons?

A: 

Mainly you need to specify your custom logic and if everything passes satisfactorily you would set args.IsValid = true; otherwise, you would set it to false. The set ErrorMessage will appear if validation fails.

The basic outline is as follows:

protected void CustomServerValidate(object sender, ServerValidateEventArgs args)
{
    if (/* custom logic */)
    {
        args.IsValid = false; // failed validation
    }
    else
    {
        args.IsValid = true; // passed validation
    }
}

For example, given radio buttons r1 and r2 you might have logic like this to ensure one of them is selected:

protected void CustomServerValidate(object sender, ServerValidateEventArgs args)
{
    if (!r1.Checked && !r2.Checked)
    {
        args.IsValid = false;
    }
    else
    {
        args.IsValid = true;
    }
}

The above could've been assigned directly in one line, but is expanded for clarity. As another example, you may have an "Other" type of button with an associated "If you selected other, please explain:" textbox. You could check if the other radio is selected, then check the textbox etc.

Ahmad Mageed
what would be the custom logic if its validating a custom control, say with an id "dpCustomControl1"?
Sophie
@Sophie: that depends on what you want to validate from the dpCustomControl1 control. Perhaps it exposes properties you want to check for specific values and depending on those values you would set the args.IsValid value accordingly.
Ahmad Mageed
ok cheers that works. But when the validation is false, the error message is not displayed even though i mentioned it in the CustomValidator tag.Why so?
Sophie
A: 

Hey,

Just specify the IsValid property of the event argument to establish whether validation was a success or not.

I don't know if you can directly link to a RadioButtonList with the CustomValidator; however, what I've done is set the ControlToValidate to a textbox or other valid control, and just have that CustomValidator validate the RadioButtonList; it still works this way, and shows up correctly when in error.

HTH.

Brian