简体   繁体   中英

Update error styling on form fields with jQuery on field blur/focus lost

I have a form that I apply error styles to if any of the field validators fail. If validation fails a tooltip is shown, this is simply a div inside of an asp validation control, eg:

<asp:RequiredFieldValidator ValidationGroup="Enquiry" Display="Dynamic" EnableClientScript="true" ID="rfvName" runat="server" ControlToValidate="txtName">
      <div class="tooltip-container name-error">
           Please enter your name
      </div>
</asp:RequiredFieldValidator>

I have some jQuery to look at these tooltips and check to see if any are visible and if they are, apply a border style to the associated field which generated the error. This all works fine, however I need to update the border style if for example the user enters valid information in the field, then the border style should be removed.

I have this working fine too, all except for one field in my form which has two tooltips, and thus two asp validation controls. A required field validator and a regular expression validator. So what I do is get a count of all of the child span elements inside of the parent td which contains the error messages, if any of these are visible then the error style should be applied (because an error tooltip is being shown), and if none of the child spans are visible, then we should remove the error class from the field because validation has passed.

For some reason this doesn't work for this one field.

Here is the JS:

jQuery(document).ready(function ($) {

    //removed...

    UpdateFieldErrorOnBlur();
});

/* Form error validation styling */

var errorSelectors = [
    ['div.name-error', 'input.name-field'],
    ['div.email-error', 'input.email-field'],
    ['div.email-error-valid', 'input.email-field'],
    ['div.enquiry-type', 'select.enquiry-field'],
    ['div.message-error', 'textarea.message-field']];

function UpdateFieldErrorOnBlur() {
var $ = jQuery;
$.each(errorSelectors, function (index, item) {
    $(item[1]).blur(function () {
        var parentContainer = $(item[0]).parents('td');
        var errorCount = parentContainer.children('span[style="display: inline;"]').length;

        if (errorCount === 0) {
            $(item[1]).removeClass('error');
        }
        else {
            $(item[1]).addClass('error');
        }
    });
});
}

function SetFieldErrorStyling() {
var $ = jQuery;
$.each(errorSelectors, function (index, item) {
    $(item[0] + ':visible').livequery(function () {
        $(item[1]).addClass('error');
    });
    $(item[0] + ':hidden').livequery(function () {
        $(item[1]).removeClass('error');
    });
});
}

Here is where I check for any child error messages within the parent <td> :

var parentContainer = $(item[0]).parents('td');
var errorCount = parentContainer.children('span[style="display: inline;"]').length;

If error count is 0 , I remove the class, else the class is applied. I have alerted the errorCount variable before the if statement and each time for the field in question it is 1 which is what you would expect yet the class is still removed if the user clears the field and then clicks outside of it to lose focus.

Can anyone help?

I am using the below function for showing validation errors using bootstrap's classes:

function highlight() {
    var $keep;

    if(typeof(Page_Validators) !== 'undefined')
    {
        $.each(Page_Validators, function (index, validator) {                
            if (!validator.isvalid) {                    
                $keep = validator.controltovalidate;   
                switch (window.event.type) {
                    case 'submit': $('body').animate({
                        scrollTop: $(document.getElementById($keep)).position().top
                    }, 1000).clearQueue(); break;
                    default: null
                }           
                $(validator).parent().addClass('has-error');
            } else {
                if ($keep != validator.controltovalidate)
                    $(validator).parent().removeClass('has-error');                                            
            }
        });
    };
};

Call:

$('form').on('keyup submit', function () {
    highlight();
});

Maybe it will save you and others some time and find it useful.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM