My Technical Notes

Friday, 27 September 2013

Implementing a simple IValidator

It is usually better to use a CustomValidator and validate using its ServerValidate event.

However, by implementing the IValidator interface, you also learn something about how ASP.NET works.

The first step would be to implement the IValidator interface, which consists of:


string ErrorMessage { get; set; }
bool IsValid { get; set; }
void Validate();

ErrorMessage is the error message that is shown to the user and is displayed in the ValidationSummary control. IsValid tells us if the validation passed or failed. Validate() is the method which will do the actual validation and set the ErrorMessage and IsValid properties, depending on whether validation passes.

This is not all. One additional step needs to be done: we need to register the validator in the OnInit and remove it OnUnload. If you don't do this then the validator will not fire. Here is the code:


#region IValidator

public string ErrorMessage { get; set; }

public bool IsValid { get; set; }

public void Validate()
{
    // do some validation here
    IsValid = false
    ErrorMessage = "It is invalid...";
}

#endregion

#region Validator registration - register this control as a validator
        
protected override void OnInit(EventArgs e)
{
    base.OnInit(e);

    // initialise the IValidator values (otherwise an exception is thrown)
    IsValid = true;
    ErrorMessage = "";

    Page.Validators.Add(this);
}

protected override void OnUnload(EventArgs e)
{
    if (Page != null)
    {
        Page.Validators.Remove(this);
    }
    base.OnUnload(e);
}

#endregion

On last thing to note is that the IValidator interface does not have a ValidationGroup property, so if your control is a standalone validation control, then it is best to inherit from BaseValidator.

No comments: