Search code examples
javascript.netrequiredfieldvalidator

Is there any way to know if a .net required field validator is enabled or disabled from js?


i am trying to get the state of the "required field validators" in an .aspx file.

When i say state i do not mean if it's valid or invalid in terms of contents but if it's enabled or not.

I know the enabled/disabled state can be set with ValidatorEnable(control, true); or ValidatorEnable(control, false);

So is there a way to know if it's enabled or disabled?

Thanks in advance.


Solution

  • You can do it on client side. So let's assume you have a required field validator as such:

    <asp:TextBox ID="txtName" runat="server" ClientIDMode="Static"></asp:TextBox>
    
    <asp:RequiredFieldValidator ID="reqValName" ControlToValidate="txtName" runat="server"
        CssClass="validation" ErrorMessage="*Required">
    </asp:RequiredFieldValidator>
    

    Then ASP.NET 4.0 generates the following JavaScript for you:

    var reqValName = document.all ? document.all["reqValName"] : document.getElementById("reqValName");
    reqValName.controltovalidate = "txtName";
    reqValName.errormessage = "*Required";
    reqValName.enabled = "False";   // <---- HERE. Set to false on server side.
    reqValName.evaluationfunction = "RequiredFieldValidatorEvaluateIsValid";
    reqValName.initialvalue = "";
    

    As you can see, reqValName.enabled = "False"; is generated if you disable the validator, but if you enable it, that line will not show.

    So you can check on the value of that variable to determine it's enabled or not. Note, it's value is a string value and you may need to put the checking JavaScript at the bottom of the page. In fact, it's a good thing to put all your JavaScript at the bottom of the page anyway (before closing body tag).

    Just FYI, if you are using ASP.NET 4.5, you can check it much easier since that attribute is put into the span element's data-val-enabled attribute instead of a JavaScript variable attribute. See the generated HTML on ASP.NET 4.5.

    <span class="validation" id="reqValName" style="visibility: hidden;" data-val-initialvalue="" 
    data-val-evaluationfunction="RequiredFieldValidatorEvaluateIsValid" data-val="true" data-val-enabled="False" 
    data-val-errormessage="*Required" data-val-controltovalidate="txtName">