Reputation: 47
I want to distinguish between required field validators and regular expression validators in my Javascript code so I can change the background color of my controls depending on the validator. Any idea how can I do it?
EDIT :
this is the script that i want to modify ( add a condition depending on required validators or regular expression validators)
Upvotes: 2
Views: 799
Reputation: 14274
If you are using client-side jQuery validation, which is the default in new ASP.NET MVC and Webforms projects, then you already have the attributes you need in HTML.
For example take a look at the following code in ASP.NET Webforms:
<div class="col-md-10">
<asp:TextBox runat="server" ID="TextBox1" CssClass="form-control" TextMode="Email" />
<asp:RequiredFieldValidator runat="server" ControlToValidate="Email"
CssClass="text-danger" ErrorMessage="The email field is required." />
<asp:RegularExpressionValidator runat="server" ControlToValidate="Email"
CssClass="text-danger" ErrorMessage="The email is not valid" />
</div>
This code produces a textbox input field and two sibling span HTML elements for the validators with corresponding data attributes
that identify the validator type, the validation function to execute etc.
So the output for the required validator is:
<span data-val-evaluationfunction="RequiredFieldValidatorEvaluateIsValid" data-val-initialvalue="" data-val="true" data-val-errormessage="The email field is required." data-val-controltovalidate="MainContent_Email"></span>
and for a regex validator it is:
<span data-val-evaluationfunction="RegularExpressionValidatorEvaluateIsValid" data-val="true" data-val-errormessage="The email field is required." data-val-controltovalidate="MainContent_Email"></span>
I have omitted some of output details for simplicity.
So you can just use the existing data attributes that ASP.NET outputs and interpret them in your javascript code.
In fact the Page_Validators array contains that data already. So you can do something like this:
switch(Page_Validators[i].evaluationfunction.name){
case "RequiredFieldValidatorEvaluateIsValid":
// do stuff for required field validators
break;
case "CustomValidatorEvaluateIsValid":
// do stuff for custom validators
break;
case "RegularExpressionValidatorEvaluateIsValid":
// do stuff for regex validators
break;
case "CompareValidatorEvaluateIsValid":
// do stuff for compare validators
break;
}
Upvotes: 2