Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQueryValidate - check if a control is required without triggering validation

I'm trying to show asterisks for controls which are required. The code was working fine with required class but now I have two fields, company and name. Only one of them is required based on other elements value. Is it possible to check if an input is required without validating the control or the form?

Example html structure:

<div class="form-group">
    <label class="control-label" for="CompanyName">Company Name</label>
    <div>
        <input type="text" id="CompanyName" name="CompanyName" class="form-control required">
    </div>
</div>

JS:

validationOptions: {
    ignore: ":disabled,:hidden",

    rules: {
        CompanyName: {
            required: function () {
                return ($("#ContactName").val().length === 0);
            }
        },
        ContactName: {
            required: function () {
                return ($("#CompanyName").val().length === 0);
            }
        }
    },

    onkeyup: function (element) {
        const $parent = $(element).parents(".form-group");

        if ($(element).valid()) {
            $parent.removeClass("invalid");
        } else {
            $parent.addClass("invalid");
        }
    },

    onfocusout: function () {
        if ($("form").valid()) {
            $("form.error").removeClass("error");
            $("form .invalid").removeClass("invalid");
        }
    },

    errorPlacement: function (error, element) {
        const $parent = $(element).parents(".form-group");

        if ($(element).hasClass("error")) {
            $parent.addClass("invalid");
        } else {
            $parent.removeClass("invalid");
        }
    },

    invalidHandler: function (event, validator) {
        $.each(validator.successList, function (index, item) {
            $(item).parents(".form-group").removeClass("invalid");
        });
        const errors = validator.numberOfInvalids();
        if (errors) {
            $.each(validator.errorList, function (index, item) {
                $(item.element).parents(".form-group").addClass("invalid");
            });
        }
    }
}

Of course I can have my code inside required callbacks above but that wouldn't be a generic solution.

I want to be able to call following function many times to update (bootstrap) asterisks on the form based on required state of the fields.

appendFormControlAsterisk: function ($panel) {
    //removeFormControlAsterisk($panel);

    let $controls = $(".form-control.required");

    $controls.each(function () {
        const $label = $(this).parents(".form-group").find(">.control-label");

        $label.html($label.html() + " <span class='text-danger'>*</span>");
    });
},

Trying to accomplish something like:

appendFormControlAsterisk: function ($panel) {
    //removeFormControlAsterisk($panel);

    let $controls = $(".form-control");

    $controls.each(function () {
        if ($(this).isRequired()) {
            const $label = $(this).parents(".form-group").find(">.control-label");

            $label.html($label.html() + " <span class='text-danger'>*</span>");
        }
    });
},
like image 621
HasanG Avatar asked Nov 06 '17 14:11

HasanG


People also ask

How do you check if jQuery validate is working?

The plugin adds a validationPlugin function to jQuery. fn , so simply check whether it exists or not; if (typeof jQuery. fn.

Does jQuery validate require a form?

The jquery validate plugin requires a form element to function, so you should have your form fields (no matter how few) contained inside a form. You can tell the validation plugin not to operate on form submission, then manually validate the form when the correct submit button is clicked.

What is jQuery validate unobtrusive?

An unobtrusive validation in jQuery is a set of ASP.Net MVC HTML helper extensions.By using jQuery Validation data attributes along with HTML 5 data attributes, you can perform validation to the client-side.

How do you check if a form is validated?

Using the email type, we can check the validity of the form field with a javascript function called… checkValidity() . This function returns a true|false value. checkValidity() will look at the input type as well as if the required attribute was set and any pattern="" tag .


1 Answers

Is it possible to check if an input is required without validating the control or the form?

There is no method as part of the jQuery Validate plugin that will return a list of declared, defined, or assigned rules. (you could look at the values inside of the settings.rules object, but this is not dynamic or comprehensive)

However, there is an undocumented method built into the plugin called .check() that will check validity without triggering any of the error messages. It's not confined to the required rule, just validity. It would effectively only be looking for the required rule during the time the field is blank.

In other words on a blank form, this method will always tell whether the field is required without triggering messages.

You must attach it to the validator object, and the argument must be a DOM element.

$('#myform').validate().check($('[name="test3"]')[0]) // <-- returns a boolean if defined

OR

var validator = $('#myform').validate({...}); // initialize plugin with options

validator.check($('[name="test3"]')[0]) // <-- returns a boolean if defined

DEMO: jsfiddle.net/we2johru/2/

Note that this method only returns a boolean when rules are defined. Without defined rules, this method will return undefined.

like image 178
Sparky Avatar answered Sep 21 '22 06:09

Sparky