I was having a problem with validating two fields in a web page the other day. The two fields were not required but it was necessary that if either field was selected then the other field would also be required.


Most of the examples I have come across simply require both fields, or require both fields based on another control. Logically speaking the request we have is an XNOR (where Field1 ='A', To Field2='B'). Only when one text box is filled out should the page flag an error.



In order to achieve this I used a CountTrueConditionsValidator from the PeterBlum Validation and More, as follows:

<vam:CountTrueConditionsValidator id="NeedBothFieldsOrNeitherField" runat="server" 
    ErrorMessageLookupID="You need both fields" 
    Minimum="1" Maximum="1" NotCondition="True" EventsThatValidate="OnSubmit"> 
        <vam:RequiredTextCondition ControlIDToEvaluate="Field1" /> 
        <vam:RequiredTextCondition ControlIDToEvaluate="Field2" /> 

In this example it counts the number of required fields from the conditions elements with the Minimum and Maximum both set to 1. This means if only one field is active this constitutes a true scenario (XOR). To make this fulfill our scenario (XNOR) the NotCondition is set to true.

Peter Blum Controls are really flexible and immersive, I will not develop any meaningful website again without them!


Technorati Tags:

Comment Section

Comments are closed.