Use Multiple Validators for a Control

Navigation:  How To... >

Use Multiple Validators for a Control

Previous pageReturn to chapter overviewNext page

The solution is to use a Validation Group as the Validator for this control.

 

Let's consider an example where a text field NGEdit1 has to comply with the following rules:

 

1.not to be empty;

2.contain a valid email address;

3.contain the same email address as the field LMDEdit2.

 

It can be achieved by use of Validation Group component which references three Validator components:

 

1.TNGRequiredFieldValidator;

2.TNGRegExpValidator;

3.TNGCompareValidator.

 

The following steps have to be performed:

 

1.Place an Error Provider component on a form, e.g TNGHintErrorProvder (NGHintErrorProvder1), set up its properties as desired.

2.Place a TNGRequiredFieldValidator component on a form (NGRequiredFieldValidator1), set its ErrorMessage property to 'Field %F should not be empty!'.

3.Place a TNGRegExpValidator component on a form (LMDRegExpValidator1), set its RegExp property to a regular expression which matches a valid email address (various solutions are possible, an example is '\b[A-Za-z0-9._%-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}\b'); set its ErrorMessage property to 'Field %F should contain a valid email address!'.

4.Place a TNGCompareValidator component on a form (NGCompareValidator1), set its RefControl property to LMDEdit2, set its ErrorMessage property to 'Field %F should match the value in NGEdit2'.

5.Place a TValidationGroup component on a form (LMDValidationGroup1).

5.1.Add an item to the Validators collection of NGValidationGroup1, set its Validator property to NGRequiredFieldValidator1;

5.2.Add an item to the Validators collection of NGValidationGroup1, set its Validator property to NGRegExpValidator1;

5.3.Add an item to the Validators collection of NGValidationGroup1, set its Validator property to NGCompareValidator1;

5.4.Add an item to the Providers collection of NGValidationGroup1, set its Provider property to NGHintErrorProvider1.

6.Set Validator property of NGEdit1 to NGValidationGroup1, ErrorMsgString property to 'Edit1'.

 

Now if the text in NGEdit1 is empty, doesn't represent a valid email address or doesn't match a value in NGEdit2, an appropriate hint message will appear; otherwise, the hint message will disappear.

 

Note: To ensure the order of the checks (and potentially make it possible to use different Error Providers for different errors), the ErrorLevel properties of Validators should be set to appropriate values (e.g. 3, 2, 1 respectively).