Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

AbdulBazith's avatar

disable required input property is not working and still validating.

Guys this question is repeated. but i found the solution almost but still cant get it. i dont know how to resolve it. thats why i posted it as new question

iam working with a project.

iam using native-validations-master downloaded it from net.

this is the link for that: https://www.cssscript.com/custom-html5-form-validator-native-validations/

It also contain demo Kindly refer it.

to perform validation i need to attach the form-validation.js file in my project and then,

in my form

document.getElementById('experience_form').validateForm();

//where experience_form is my form name and validateForm is function name in the validation js file

my problem is i have hidden input fields in this form. those also validated so that i cant submit the form.

if that input fields are visible then only it must be validated. how to do that?

i searched in net and did this


  document.getElementById('experience_form').validateForm(
        {
         ignore: "#hidden"
         }
  );

but not worked. still it is validating

i referred in net but most of the solutions are based on jquery.

Then what i decided is to check in chrome dev tools. i got a solution that even the input field is hidden the required property is enabled. so i decided to disable the property.

this is the image when the required property is enabled and the dropdown down is given corectly. the the below given image. notice period is the field which will be hidden.

Currently in the below image it is not hidden and the required property is also enabled

Refer this image: https://imgur.com/a/3oPp27d

The input field is not hidden so the required property is also enabled. it is validating. and see down i marked the class name is changed to has-success. it is changed to success with the help of form-validation.js file.

Now the notice period field is with error refer the below image.

Refer the image: https://imgur.com/a/6vabvcd

in the above image see that when error is there then the class name changed to has- error and also error message is displayed in tag <span>Please select an option form the list</span>

so what i planned is to disable the required property in the notice period contol.

I have a radio button with yes and no options. when yes is clicked the comtol is enabled and when no is clicked the contol will be disabled.

so when changing the radio button to no i placed the below code.

  document.getElementById("notice_period").required = false;

everything works fine. the required property is disabled. but still the form is not submitting.

At-last i found the solution that the span tag is fault here.

Refer the image: https://imgur.com/a/GoF8Pdj

See here when the no radio button is clicked the notice period control is hidden and also see the dev tool, the required property also disabled. but note that the span tag is still there. thats the fault here. The span tag is present so the form is not submitted.

IF i delete the span tag in the dev tool then if i click the sumbit its working.

i dont know how could i disble the span tag.

The span tag is present only when there is error.

this the form-validation.js file

/*
* Learn about Javascript Basic validation API https://www.w3schools.com/js/js_validation_api.asp
* Learn about Data attributes: https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/dataset
*
* You can can custom error messages with these data attributes
* data-require-error        used to display custom message for required field
* data-pattern-error        used to display custom message for field with pattern attribute
*
* Here is a list of configuration variables that can be passed while initializing form validation
* The value for these variables will override default value if passed otherwise default value will be used.
*
* invalidEmail                      :Message that you want to display in case of invalid input
* invalidNumber                     :Message that you want to display in case of invalid input
* invalidPhone                      :Message that you want to display in case of invalid input
* invalidOption                     :Message that you want to display in case of invalid input
* invalidCheckbox                   :Message that you want to display in case of invalid input
* fillOut                           :Message that you want to display in case of invalid input
* invalidRange                      :Message that you want to display in case of invalid input
* invalidLength                     :Message that you want to display in case of invalid input
* invalidGroupOption                :Message that you want to display in case of invalid input
* messageWrapperTag                 : valid HTML element that you want to use to wrap error message
* successClass                      : class name
* errorClass                        : class name
* closestTagSelector                : any valid selector, it can be an id OR class i.e  '#form-group' OR  '.form-group'
*
 */
var EmailMessage = "Please enter a valid email address.";
var NumberMessage = "Please only enter numbers.";
var PhoneMessage = "Please enter a valid phone number.";
var OptionMessage = "Please select an option from the list.";
var CheckboxMessage = "Please check the required box.";
var FillOutMessage = "Please fill out";//field name or 'this field' will be appended to this with a space.
var RangeMessage = "Please input a value between";//field min and max attribute value will be appended to this.
var LengthMessage = "Input character should be between";//field min and max attribute value will be appended to this.
var OptionGroupMessage = "Please select at least one option";
///*{0} will be replaced with the actual message later on before displaying.*/
var MessageTag = "<span class='help-block' id='help-block'>{0}</span>";
var SuccessClass = "has-success";
var ErrorClass = "has-error";
var HelpBlockSelector = ".help-block";
var ClosestTagSelector = ".form-group";

var args = {
    invalidEmail: "",
    invalidNumber: "",
    invalidPhone:"",
    invalidOption:"",
    invalidCheckbox:"",
    fillOut:"",
    invalidRange:"",
    invalidLength:"",
    invalidGroupOption:"",
    successClass:"",
    errorClass:"",
    closestTagSelector:"",
    messageWrapperTag: "<span class='help-block' id='help-block'></span>"
};

Element.prototype.validateForm = function (args) {

    if (args !== undefined) {
        //override variable values if provided and not empty
        if (args.invalidEmail !== undefined && args.invalidEmail !== '') EmailMessage = args.invalidEmail;
        if (args.invalidNumber !== undefined && args.invalidNumber !== '') NumberMessage = args.invalidNumber;
        if (args.invalidPhone !== undefined && args.invalidPhone !== '') PhoneMessage = args.invalidPhone;
        // if (args.invalidOption !== undefined && args.invalidOption !== '') OptionMessage = args.invalidOption;
        if (args.invalidCheckbox !== undefined && args.invalidCheckbox !== '') CheckboxMessage = args.invalidCheckbox;
        if (args.fillOut !== undefined && args.fillOut !== '') FillOutMessage = args.fillOut;
        if (args.invalidRange !== undefined && args.invalidRange !== '') RangeMessage = args.invalidRange;
        if (args.invalidLength !== undefined && args.invalidLength !== '') LengthMessage = args.invalidLength;
        if (args.invalidGroupOption !== undefined && args.invalidGroupOption !== '') OptionGroupMessage = args.invalidGroupOption;
        //insert {0} in between wrapper tag that will be replaced with actual message later on before displaying.
        if (args.messageWrapperTag !== undefined && args.messageWrapperTag !== '') MessageTag = args.messageWrapperTag.replace("></", ">{0}</");
        if (args.successClass !== undefined && args.successClass !== '') SuccessClass = args.successClass;
        if (args.errorClass !== undefined && args.errorClass !== '') ErrorClass = args.errorClass;
        if (args.closestTagSelector !== undefined && args.closestTagSelector !== '') ClosestTagSelector = args.closestTagSelector;
    }

    var form = this;
    this.addEventListener("invalid", function (event) {
        event.preventDefault();
    }, true);
    // Support Safari, iOS Safari, and the Android browser—each of which do not prevent
    // form submissions by default
    this.addEventListener("submit", function (event) {
        if (!this.checkValidity()) {
            event.preventDefault();
        }
    });
    //********************************************** for blur event of each control
    var allControls = this.querySelectorAll("input:not([type='submit']):not([name$='[]']), select, textarea");
    for (var i = 0; i < allControls.length; i++) {
        var input = allControls[i];
        //bind blur event for every field in the form
        input.addEventListener("blur", function (event) {
            //get parent of object
            var inputParent = event.target.parentNode;
            //Following if block is only for styled select boxes and custom date picker
            if (inputParent.classList.contains('old') || inputParent.classList.contains('date')) {
                inputParent = inputParent.closest(ClosestTagSelector)
            }

            //get help block and remove it if already added.
            var spanError = inputParent.querySelector(HelpBlockSelector);
            if (spanError) {
                inputParent.removeChild(spanError);
                inputParent.closest(ClosestTagSelector).classList.remove(ErrorClass);
                inputParent.closest(ClosestTagSelector).classList.add(SuccessClass);
            }
            //validate the current field and based on result add/remove the error message
            if (!event.target.validity.valid) {
                inputParent.closest(ClosestTagSelector).classList.add(ErrorClass);
                inputParent.closest(ClosestTagSelector).classList.remove(SuccessClass);
                inputParent.insertAdjacentHTML("beforeend", MessageTag.replace("{0}", GetMessage(event.target)));
            } else {
                inputParent.classList.remove(ErrorClass);
            }
        });
    }

    //get input type checkbox(s) that belongs to a group with name attribute
    var onlyCheckBoxGroups = this.querySelectorAll("input[name$='[]']");
    var checkBoxArray = [];
    var checkBoxNames = [];
    var singleName = '';
    //iterate checkboxes and prepare a list of group names and their relevant checkboxes
    for (var i = 0; i < onlyCheckBoxGroups.length; i++) {
        if (singleName !== onlyCheckBoxGroups[i].name) {
            if (checkBoxNames.length > 0) {
                checkBoxArray.push(checkBoxNames);
                checkBoxNames = [];
            }
            singleName = onlyCheckBoxGroups[i].name;
        }
        checkBoxNames.push(onlyCheckBoxGroups[i]);
        if ((onlyCheckBoxGroups.length - 1) === i) {
            checkBoxArray.push(checkBoxNames);
            checkBoxNames = [];
        }
    }
    for (var j = 0; j < checkBoxArray.length; j++) {
        var checkBoxes = checkBoxArray[j];
        var groupParent = checkBoxes[j].parentNode;
        //bind change and blur event foreach checkbox whose parent has attribute required
        if (groupParent.getAttribute('required') != null) {
            for (i = 0; i < checkBoxes.length; i++) {
                checkBoxes[i].addEventListener("change", function (event) {
                    checkBoxGroupValidate(event)
                });
                checkBoxes[i].addEventListener("blur", function (event) {
                    //get the next element that get focus after the recently triggered blur event
                    if (event.relatedTarget) {
                        //and if the next element is member of another group or another item then validate value
                        //for previous group
                        if (event.target.getAttribute('name') !== event.relatedTarget.getAttribute('name')) {
                            checkBoxGroupValidate(event);
                        }
                    }
                });
            }
        }
    }

    /*
    * This function validates the value for a checkbox group that is marked required.
    */
    function checkBoxGroupValidate(event) {
        //get all checked checkboxes for a group and if its null then mark it invalid or valid
        var totalChecked = event.target.parentNode.querySelector("input[name$='[]']:checked");
        if (totalChecked === null) {
            var errorMessage = '';
            if(event.target.dataset.requireError){
                errorMessage = event.target.dataset.requireError;
            }else if(event.target.parentNode.dataset.requireError){
                errorMessage = event.target.parentNode.dataset.requireError;
            }else {
                errorMessage = OptionGroupMessage;
            }
            event.target.parentNode.classList.remove(SuccessClass);
            event.target.parentNode.classList.add(ErrorClass);
            if (event.target.parentNode.querySelector(HelpBlockSelector) === null) {
                event.target.parentNode.insertAdjacentHTML("beforeend", MessageTag.replace("{0}", errorMessage));
            }
        } else {
            event.target.parentNode.classList.remove(ErrorClass);
            event.target.parentNode.classList.add(SuccessClass);
            var spanError = event.target.parentNode.querySelector(HelpBlockSelector);
            if (spanError !== null) {
                event.target.parentNode.removeChild(spanError)
            }
        }
    }

    //****************************************** for click event of submit button
    var submitButton = this.querySelector("input[type=submit]");
    submitButton.addEventListener("click", function (event) {
        var errors = 0;
        for (var j = 0; j < checkBoxArray.length; j++) {
            var checkBoxes = checkBoxArray[j];
            var groupParent = checkBoxes[j].parentNode;
            if (groupParent.getAttribute('required') != null) {
                var totalChecked = groupParent.querySelector("input[name$='[]']:checked");
                if (totalChecked === null) {
                    errors++;

                    groupParent.classList.remove(SuccessClass);
                    var errorMessage = groupParent.querySelector("input[name$='[]']").getAttribute('data-requireError');
                    groupParent.classList.add(ErrorClass);
                    if (groupParent.querySelector(HelpBlockSelector) === null) {
                        groupParent.insertAdjacentHTML("beforeend", MessageTag.replace("{0}", errorMessage));
                    }
                }
            }
        }
        var invalidFields = form.querySelectorAll(":invalid:not(fieldset)"),
            errorMessages = form.querySelectorAll(HelpBlockSelector),
            myParent;

        // Remove any existing messages
        for (var i = 0; i < errorMessages.length; i++) {
            //errorMessages[ z ].parentNode.removeChild( errorMessages[ z ] );
        }
        for (var i = 0; i < invalidFields.length; i++) {
            myParent = invalidFields[i].parentNode;
            //Following if block is only for styled select boxes
            if (myParent.classList.contains('old') || myParent.classList.contains('date')) {
                myParent = myParent.closest(ClosestTagSelector)
            }
            var spanError = myParent.querySelector(HelpBlockSelector);
            if (spanError) {
                myParent.removeChild(spanError);
                myParent.closest(ClosestTagSelector).classList.remove(ErrorClass);
            }
            if (!invalidFields[i].validity.valid) {
                myParent.closest(ClosestTagSelector).classList.add(ErrorClass);
                myParent.insertAdjacentHTML("beforeend", MessageTag.replace("{0}", GetMessage(invalidFields[i])));
            } else {
                myParent.closest(ClosestTagSelector).classList.remove(ErrorClass);
            }
        }

        // If there are errors, give focus to the first invalid field
        if (invalidFields.length > 0) {
            invalidFields[0].focus();
        } else {
            if (errorMessages.length === 0) {
                this.submit();
            } else {
                event.preventDefault();
            }
        }
    });
};

/**
 * @return {string}
 */
function GetMessage(element) {
    //the data attribute with multiple dashes(-) will be obtained using camelCase conversion i.e data-abc-def corresponds to the key abcDef
    //If data-requireError or data-patternError are defined
    if (element.dataset.requireError || element.dataset.patternError) {
        if (element.validity.valueMissing === true) {
            return element.dataset.requireError;
        }
        else {
            return element.dataset.patternError;
        }
    } else {
        //if error message are not defined via data attributes then use default OR generic messages.
        var name = element.nodeName,
            type = element.type;
        //assign name to type variable if element is not an input element to use within switch case
        if (name !== 'INPUT') {
            type = name;
        }
        var errorMessageToShow = '';
        switch (type) {
            case 'email':
                if (element.validity.typeMismatch === true) {
                    errorMessageToShow = EmailMessage;
                } else {
                    errorMessageToShow = element.validationMessage;
                }
                break;
            case 'tel':
                if (element.validity.typeMismatch === true) {
                    errorMessageToShow = PhoneMessage;
                } else {
                    errorMessageToShow = element.validationMessage;
                }
                break;
            case 'SELECT':
            case 'radio':

                if (element.validity.valueMissing === true && m=== true ) {

                    alert(m);

                    errorMessageToShow = OptionMessage;
                }
                else {
                    errorMessageToShow = element.validationMessage;
                }
                break;
            case 'checkbox':
                if (element.validity.valueMissing === true) {
                    errorMessageToShow = CheckboxMessage;
                } else {
                    errorMessageToShow = element.validationMessage;
                }
                break;
            default:
                if (element.validity.valueMissing === true) {
                    /* Required field left blank. */
                    errorMessageToShow = FillOutMessage + ((element.name) ? (' ' + element.name + '.') : ' this field.');
                } else if (element.validity.typeMismatch === true) {
                    /* element's value is invalid per its type attribute */
                    errorMessageToShow = element.validationMessage;
                } else if (element.validity.patternMismatch === true) {
                    /* element's value does not match its pattern attribute */
                    if (element.pattern === '\d*') {
                        errorMessageToShow = NumberMessage;
                    } else {
                        errorMessageToShow = element.validationMessage;
                    }
                } else if (element.validity.rangeOverflow === true || element.validity.rangeUnderflow === true) {
                    /*element's value does not match its min/max attribute*/
                    var max = element.getAttribute('max'),
                        min = element.getAttribute('min');
                    errorMessageToShow = RangeMessage + " " + min + "-" + max + ".";
                } else if (element.validity.tooLong === true || element.validity.tooShort === true) {
                    //element's value not match with minimum/maximum length attribute
                    var maxLength = element.getAttribute('maxlength'),
                        minLength = element.getAttribute('minlength');
                    errorMessageToShow = LengthMessage + " " + minLength + "-" + maxLength + ".";
                } else if (element.validity.stepMismatch === true) {
                    errorMessageToShow = element.validationMessage;
                } else {
                    /* Default message. */
                    errorMessageToShow = element.validationMessage;
                }
                break;
        }
        return errorMessageToShow;
    }
}

Iam stuck that where i should change that.

i can change the validation. but this validation is good for me and in most of the forms i applied this. just for only two forms iam facing due to hidden fields. if i need to change the validation package. then i need to change it for all form. thats why i am stressing in this same form.

i think everyone understood the question. sorry for these much toooo large question

Kindly some one help please. 2 days i am sitting with this problem.

0 likes
7 replies
lostdreamer_nl's avatar

looking at the library, it doesnt have any options to 'not validate hidden inputs'

But it's an easy change.....

line 89 in js/form-validation.js:

var allControls = this.querySelectorAll("input:not([type='submit']):not([name$='[]']), select, textarea");

Change it into:

var allControls = this.querySelectorAll("input:not([type='submit']):not([type='hidden']):not([name$='[]']), select, textarea");

That should keep the library from checking hidden input fields.

"if i need to change the validation package. then i need to change it for all form"

  • Can you tell me an example where you would want to validate a hidden input (that the user cannot change) ?

I think its safe to make this change, actually, the original author of the package should have come accross this problem, but you took a package that was written in 1 go, 10 months ago, no updates, no issues, no nothing..... Normally I'd try to stick to packages that have been more thoroughly tested.

1 like
munazzil's avatar

In that select-form html class remove the required word.

1 like
AbdulBazith's avatar

@munazzil @lostdreamer_nl thank you for your responses

@munazzil yes u are right. we can remove that required property from that control. but i need that. i will explain it clearly

@lostdreamer_nl i understood that, but what you saying whether to change that code or not in line number 89..

i couldnt get these lines I think its safe to make this change, actually, the original author of the package should have come accross this problem, but you took a package that was written in 1 go, 10 months ago, no updates, no issues, no nothing..... Normally I'd try to stick to packages that have been more thoroughly tested.

and i have changed that coding still it not working..

this is my control


<div class="row mb-4" style="display: none;" id="np">
                    <div class="col-md-3"><label for="sel1">Notice Period</label></div>
                    <div class="col-md-3">
                        <div class="form-group" id="frm_grp" >
                            <select class="form-control" id="notice_period" name="notice_period" required >
                                <option value="">Select Notice Period</option>
                                <option value="15 days or Less"> 15 days or Less</option>
                                <option value="1 Month"> 1 Month</option>
                                <option value="2 Months">2 Months</option>
                                <option value="3 Months">3 Months</option>
                                <option value="More than 3 Months">More than 3 Months</option>
                            </select>
                        </div>
                    </div>
                </div>



there is a question in my form whether his working company is present or not

if he clicks yes then the notice period control will be visible to him. so he need to select the notice period.

if he clicks no then some other text box which makes to enter him the date will be shown

Refer this image: https://imgur.com/a/YKLlY7y

see the above image i have changed the code as what you said.

and see this image: https://imgur.com/a/PaoCzpR

see the required is disabled, and the control is hidden but still the error msg is there.

Actually initially when form loads it works fine. if the seeker clicks no then that control is hidden and everthing is fine.

But just i tested the application by clicking yes then the control is visible then i left it blank so it is validated and error msg is shown, and then i clicked no so that the cotrol became hidden, but that error msg not vanishing.

Simply to if that control is validated with visible and then that control becomes hidden means , its not working.

that the problem here.

i dont know what i need to doo.

1 like
lostdreamer_nl's avatar

Aah, so the input field is getting hidden / unhidden by the user and it is visible when the page renders......

The validation library you are now using sets up the validation when the page loads. So if you have visible inputs at that point, they will be validated even if you turn them into hidden inputs later ;).

This library can not be used in the way you want, what you want is a library that only starts validating when you try to submit the form ;)

About the part you didn't get, what I ment was: Trying to validate hidden inputs is very stupid, so the original maker of that package should have found that bug already and fixed it.

The reason he didn't find the bug was because this package was written, uploaded, and abandoned. It's not getting updated, and it's hardly in use by anyone.

Always try to go with packages that have some more commits, a few bug reports and fixes, at least you'll know that the package is in use and getting updates when needed.

1 like
AbdulBazith's avatar

@lostdreamer_nl thank you thank you soo much for your clear explanation..

you understood what my expectation and what my problem and you gave me clear response and suggestion..

I know its better to write validation of our own, but i know only to display the validated error msg in alert box.

But my boss is expecting the error msg to be somewhat good.

i think you might watched the demo of the package which i took. it looks good. if input field is empty then the box becomes red and a cross mark is displayed.

Can u suggest me any package for my validation process please..

dont think that everything i am asking to you, iam in dead end so only.

and kindly if possible please refer my another post which is related to javascript

refer: https://laracasts.com/discuss/channels/laravel/how-to-check-if-values-are-repeated-from-controller-laravel

Question: How to check if values are repeated from controller laravel

please please

1 like
lostdreamer_nl's avatar
Level 53

A few years ago I ran into this package: https://github.com/proengsoft/laravel-jsvalidation

It seems even more solid now, you can use the FormRequest validation of laravel which you should already be using in the backend to validate your user input: https://laravel.com/docs/5.7/validation#form-request-validation

It has ways to load that validation array into JS validations.

This way your backend and frontend validation will always be the same.

Also, it might be that the package Former ( https://github.com/formers/former ) could help you out a lot in writing the forms a lot quicker:

Former::select('education')->options($educations->pluck('name', 'id'));

Will create a bootstrap label + selectbox + select the current option in case of an edit form + shows the error messages after a failed validation.

At the very least, it can help make up for some of the lost time spend on this validation.

1 like

Please or to participate in this conversation.