Skip to content

Documentation is missing how to reset the form validation #25626

Closed

Description

@burzum

I haven't found a solution... What annoys me the most is that the documentation does not show how to reset or disable validation. I shouldn't have to search the web for this common use case.

I want to clear the form after submission but the validation immediately jumps in and validates the now empty form fields again, resulting in showing errors.

	function formValidation() {
		// Validation -> https://getbootstrap.com/docs/4.0/components/forms/#validation
		// Fetch all the forms we want to apply custom Bootstrap validation styles to
		var forms = document.getElementsByClassName('needs-validation');
		// Loop over them and prevent submission
		var validation = Array.prototype.filter.call(forms, function (form) {
			form.addEventListener('submit', function (event) {
				if (form.checkValidity() === false) {
					event.preventDefault();
					event.stopPropagation();
					$(form).addClass('is-invalid');
				} else {
					$(form).addClass('is-valid');
				}
				form.classList.add('was-validated');
			}, false);
		});
	}

	function contactForm() {
		// Honeypot
		let honeypot = $('#contact-website');
		let contactForm = $('#contact-form');

		honeypot.parent('.form-group').hide();
		honeypot.removeAttr('required');

		contactForm.on('submit', (event) => {
			event.preventDefault();

			if (!contactForm.hasClass('is-valid')) {
				return;
			}

			$.ajax({
				type: 'POST',
				url: 'contact.php',
				data: contactForm.serialize(),
				success: () => {
					$('#contact-form input').val('');
					$('#contact-form textarea').val('');
					$('#modal').modal('show');
				}
			});
		});
	}

Activity

  1. bkdotcom commented on Feb 14, 2018

    @bkdotcom
    Contributor

    not a bootstrap issue?
    try $('#contact-form input').val('').trigger("change");
    maybe add $('#contact-form input').each(function(){ this.setCustomValidity(''); }); to the mix

  2. burzum commented on Feb 14, 2018

    @burzum
    Author

    @bkdotcom well, I think it is, because why is there no way to en/disable validation? I couldn't find anything in the docs related to the JS part of the validation besides the part I've already linked.

  3. patrickhlauke commented on Feb 14, 2018

    @patrickhlauke
    Member

    bootstrap doesn't provide validation per se. it provides styles that hook into the browser's own validation. how to trigger or reset the browser's own validation is therefore slightly outside of what bootstrap itself does (though having an example of how it's reset may be useful, granted...but that's just basic JS, not really related to bootstrap itself)

  4. burzum commented on Feb 14, 2018

    @burzum
    Author

    @patrickhlauke OK, if it's so basic, just point me to any place that shows how to disable the constraint API validation temporary for a form. :) I'm browsing the Mozilla docs for some time now without success and I'm about to drop this in favor of the Jquery Validation plugin. I've already read this and this without finding what I'm looking for. I can't even find what I'm looking for on Stackoverflow and Google, the search results always come up with the novalidate attribute. :(

  5. patrickhlauke commented on Feb 14, 2018

    @patrickhlauke
    Member

    i did not say it's basic. i said it's a feature of HTML and the browser, not a bootstrap feature, and it's not necessarily the point of bootstrap's documentation how to use HTML and its related APIs.

    how to disable the browser's native validation/constraints API for a form? add novalidate to the form (or formnovalidate to a specific form control) https://www.w3.org/TR/html53/sec-forms.html#element-attrdef-form-novalidate [edit: corrected, as i got myself mixed up: it's indeed novalidate on the form is correct; on individual form controls, it's formnovalidate. confusing, but yeh...]

  6. burzum commented on Feb 14, 2018

    @burzum
    Author

    @patrickhlauke let me try that, if that works it should be added to the docs besides the correction of the novalidate. This took me now almost 2h in total. :(

    Tried it: Doesn't work either.

  7. patrickhlauke commented on Feb 14, 2018

    @patrickhlauke
    Member

    looking at your thread opener, you're doing some custom javascript. please provide a live working example (in something like codepen or similar), but again fundamentally this does not look like a bootstrap issue - but related to either your javascript, or how browsers handle validation for forms like yours that are not really submitting, but rather ajaxing things.

  8. burzum commented on Feb 14, 2018

    @burzum
    Author

    @patrickhlauke https://codepen.io/anon/pen/rJGmoj

    The only custom JS I've added in the pen above is this:

    let form = $('#test-form');
    
    form.find('button').on('click', (event) => {
      form.find('input, select, textarea').val('');
    });

    Everything else is a copy and paste job from the bootstrap docs, except the form id I've added. You can see how it invalidates all fields after setting them to no value. I would like to prevent validation and then put it back on when I reset the field.

    Yes, I agree it is not directly a bootstrap issue but this is something many people probably will run into because bootstrap favors the vanilla constraint API in the docs. I'm pretty surprised there seems to be no simple way to do what I want because I think it is not that unusual?

  9. bkdotcom commented on Feb 14, 2018

    @bkdotcom
    Contributor

    @burzum are you using angular? what extensions/plugins/modules/components (whatever anguar calls plugins nowdays)? Probably some form validation stuff going on with your angular framework/stack

  10. burzum commented on Feb 14, 2018

    @burzum
    Author

    @bkdotcom check the codepen link (same as above), no, I don't use Angular or anything else. Just jquery. We're using Vue.js at work but I need this form for a simple static HTML5 page I'm working on for my photography hobby.

  11. patrickhlauke commented on Feb 14, 2018

    @patrickhlauke
    Member

    in your codepen, you're clearing the form fields on the click. this is executed before the validity check on submit. so in essence, the user can fill in the form correctly, click submit, then just before the validation kicks in, you're emptying the fields again...making form submission fail and the errors appear...

  12. patrickhlauke commented on Feb 14, 2018

    @patrickhlauke
    Member

    if you are executing custom javascript on submission, you should really do the validation and your own logic in a single custom code block, rather than relying on the javascript example used in the docs to prevent submission on errors AND also hooking in your own code (on the submit event, looking at your thread starter code), as i'd hazard a guess that there are likely inconsistencies of when one or the other execute.

  13. burzum commented on Feb 14, 2018

    @burzum
    Author

    @patrickhlauke updated the codepen to use submit, doesn't work either:

    form.on('submit', (event) => {
      form.find('input, select, textarea').val('');
    });

    Well, I thought the docs provide a generic approach to all forms on a page. I just have one form in my case but there can be cases with many forms on a page.

  14. patrickhlauke commented on Feb 14, 2018

    @patrickhlauke
    Member

    if you form wasn't doing custom AJAX stuff and not actually submitting itself, the code provided in the documentation would work just fine. once you go off-piste with non-standard behaviour, then yes things will get bumpy. but we can't include (nor foresee) all those situations in the documentation.

    anyway, even though this is not a general case, but rather something that is down to your own implementation...here's a rough solution https://codepen.io/patrickhlauke/pen/wyreOg

  15. added a commit that references this issue on Jun 27, 2018
  16. cia05rf commented on Mar 30, 2020

    @cia05rf

    Just had this issue myself. Came up with a bit of a hacky way to solve it but it works:

            jQueryFormElem.on("submit",function(e){
                if (this.checkValidity() !== false) {
                    e.preventDefault();
                    e.stopPropagation();
                    //Reset the form
                    $(this)[0].reset();
                    setTimeout(() => {$(this).attr('class',"needs-validation")},1); //timeout allows for 'was-validated' to be added then removed.
                }
            });
    
  17. kulketan commented on Apr 28, 2021

    @kulketan

    I'm using below code to reset the form after successful validation and not get the red border.

    var forms = document.getElementsByClassName('needs-validation');
    		// Loop over them and prevent submission
    		var validation = Array.prototype.filter.call(forms, function (form) {
    			form.addEventListener('submit', function (event) {
    				if (form.checkValidity() === false) {
    					event.preventDefault();
    					event.stopPropagation();
    				} 
    				form.classList.add('was-validated');
                                    if(form.checkValidity() === true){
                                            //for is validated successfully. Here you can write ajax call or whatever
                                            form.classList.remove("was-validated");
                                            form.reset();
                                    }
    			}, false);
    		});
    
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions