Reputation: 1398
I'm trying to use CustomValidator
on a drop down list within my webpage, and it isn't being triggered correctly on form submit as the colour of the dropdown doesn't change. I've got the same validation working on text boxes just fine, but I'm obviously doing something wrong for drop downs and would appreciate any help!
I used this Change Text Box Color using Required Field Validator. No Extender Controls Please
And I think what's happening is that the validation is triggered on the form submit. The logic in the .cs file and the javascript file is the same, so that if javascript is disabled by the user the validation should still kick in.
The first value in the dropdown is "Select a value" so my validation says as long as it's not that value proceed.
.aspx file
<p class="form-row">
<asp:DropDownList ID="valueDropDown" runat="server" CssClass="tablet" ></asp:DropDownList>
<asp:CustomValidator ID="CustomValidator4" runat="server" ErrorMessage=""
ControlToValidate="valueDropDown" ClientValidationFunction="ValidateDD"
OnServerValidate="CustomValidator4_ServerValidate"
ValidateEmptyText="True" >
</asp:CustomValidator>
</p>
.cs file
protected void CustomValidator4_ServerValidate(object source, ServerValidateEventArgs args)
{
bool is_valid = valueDropDown.Text != "Select a value";
valueDropDown.BackColor = is_valid ? Color.White : Color.Red;
args.IsValid = is_valid;
}
Javascript
function ValidateDD(source, args) {
var is_valid = $("#valueDropDown").val() != "Select a value";
$("#valueDropDown").css("background-color", is_valid ? "white" : "#EEB4B4");
args.IsValid = is_valid;
}
Any help would be appreciated - I'm really stuck as to why this isn't working!
EDIT
Ok following on from what @Gian-Paolo has said I've now removed the first required validator from my code but I'm still getting the same problem. The colour is still not being applied.
This has now been removed:
<asp:RequiredFieldValidator ID="ValidatorDD" ControlToValidate="valueDropDown" runat="server" InitialValue="-1" Text="* Please select a value" ErrorMessage="" CssClass="error" Display="Dynamic" ></asp:RequiredFieldValidator>
Upvotes: 0
Views: 268
Reputation: 4249
You are attaching to the same valueDropDown control 2 validators:
<asp:RequiredFieldValidator ID="ValidatorDD" ControlToValidate="valueDropDown"... >
</asp:RequiredFieldValidator>
<asp:DropDownList ID="valueDropDown" runat="server" CssClass="tablet" >
</asp:DropDownList>
<asp:CustomValidator ID="CustomValidator4" ...
ControlToValidate="valueDropDown" ClientValidationFunction="ValidateDD"...>
</asp:CustomValidator>
I assume javascript will run first validator code, and since that return false stop evaluating the following ones. Same for Server code if JS is disabled in the browser. Try to remove the requiredFieldValidator.
Also, refine your question: what do you mean with " (my customavlidator) isn't being picked up"? (just realized now that I'm not sure I understood your question)
Upvotes: 1