Search code examples
javascriptjqueryasp.netrequiredfieldvalidator

validating required fields with asp.net required field validators using jquery


HTML:

<fieldset>
    <p>
       <label>SOME LABEL</label><span class="required"> *</span>
    </p>
    <input type="text" id="txtBox">
</fieldset>

Using jQuery i am trying to get "span.required" and add a class "missing" (changes color to red).

JQuery Code:

$('#txtBox').closest('fieldset').find('span.required').addClass('missing');

JQUERY CODE FOR required field validator in ASP.NET:

for (var i = 0; i < Page_Validators.length; i++) {
            var val = Page_Validators[i];
            var ctrl = document.getElementById(val.controltovalidate);
            if (ctrl != null && ctrl.style != null) {
                if (!val.isvalid) {
                    ctrl.closest('fieldset').find('span.required').addClass('missing');
                }
                else {
                    //alert('no error');

                }
            }
        }

ERROR via Console: object [ctrl object - the textbox] has no method closest

i have tried different interations using "find" "parent" etc. but nothing i try seems to work.

What is wrong with my code? I cannot grab that span.required

Thank you to everyone's input, I have learned a lot from each of your input. EVERYONE's answer has valid and working code, however only the selected provided the solution.


Solution

  • First off, there are a couple of changes in your HTML that you should make which will not only help you solve this issue, but will also make for cleaner, more valid code:

    1. Add a for attribute to all of your <label> tags that pairs them with the input that they match (this really should always be done with labels), and
    2. Move the <span class="required"> *</span> inside the label (since it really is part of the label)

    The resulting code would look like this:

    <fieldset>
        <p>
            <label for="txtBox">SOME LABEL<span class="required"> *</span></label>
        </p>
        <input type="text" id="txtBox">
    </fieldset>
    

    Once you've done that, what you are trying to accomplish becomes much easier:

    Instead of:

    ctrl.closest('fieldset').find('span.required').addClass('missing');
    

    . . . you can use the id of the input (val.controltovalidate) as part of a JQuery selector to find the related label directly:

    var $targetLabel = $("label[for='" + val.controltovalidate +"']")
    $targetLabel.find('span.required').addClass('missing');
    

    I've used this many times to pair validations with the labels of the field that is being validated . . . quick and clean. :)

    Edit: I split up the last JS piece to keep it from scrolling, but it could be one line. :)