Re-using Inbuilt Validation Scripts
Sometimes we require our validator control in ASPX page to be called from Javascript. i.e explicitly calling a inbuilt validator script. A practical example will be calling a validator that belongs to a different validation group from a button click that does not belong to that validation group. This simple trick will enable you to use those validators to be reused using Jscript.
Using CompareValidator script
For example, consider we have 2 textbox, one for entering your age (txtYourAge)) and another one for entering your father's age (txtFathersAge). We will require a CompareValidator that will validate for father's age which should be greater than your age. Consider this 2 textboxes, compare validators belongs to a same Validation group (Say AgeGroup).
<asp:TextBox ID="txtFathersAge" runat="server" ValidationGroup="AgeGroup"></asp:TextBox>
<asp:TextBox ID="txtYourAge" runat="server" ValidationGroup="AgeGroup"></asp:TextBox>
<asp:CompareValidator ID="comvalAgeCompare" runat="server" ControlToCompare="txtFathersAge"
ControlToValidate="txtYourAge" ErrorMessage="Father Age shld be greater" Operator="GreaterThan" Type="Integer" ValidationGroup="AgeGroup"></asp:CompareValidator>
<asp:Button ID="btnCalculateDifference" ValidationGroup="AgeGroup" runat="server" Text="Calculate Difference" />
Now the validation will fire only for the postback caused by the control in the ValidationGroup "AgeGroup".
Suppose, if you want to call this validator on a button click that does not belongs to this ValidationGroup "AgeGroup" we can go ahead by using the following script to achieve this without a separate validator or a custom Jscript.
function IsAgeRangeValid()
{
var val = document.getElementById('comvalAgeCompare');
return CompareValidatorEvaluateIsValid(val);
}
where "comvalAgeCompare" is the ID of the CompareValidator on the ASPX page.
CompareValidatorEvaluateIsValid is the Jscript validation function of ASP.Net CompareValidator that will be generated by the ASP.Net runtime. This function will return true if the validation succeeds and false for failure.
Usage:
<asp:Button ID="btnSaveData" OnClientClick="return IsAgeRangeValid();" runat="server" Text="Save" />
|