HTML browser validation when submitting using javascript?

Is it possible to keep default HTML validation when submitting via Javascript?

I mean, if I submit the form using this JS method:

document.getElementById("mc-embedded-subscribe-form").submit(); 

How to save defualt error messages thrown by browser?

enter image description here

One of the solutions I was thinking of uses the following:

 <form onSubmit="return somefunction()"> 

But since the API returns success inside the closure function, I cannot use this method.

+6
source share
3 answers

according to my understanding of your question, the html check is not enough to stop the feed, you need to check the correct input of data in javascript before sending.

eg

 if (!empty(username)) { document.getElementById("mc-embedded-subscribe-form").submit(); } 
+2
source

HTML5 also specifies a JS API that can be used to interact with forms / elements regarding validation status: https://www.w3.org/TR/html5/forms.html#the-constraint-validation-api

Thus, the easiest way to achieve this would be to call the checkValidity method of your form and only submit it when it returns true.

Something like that:

 function submitIfValid() { var form = document.getElementById("mc-embedded-subscribe-form"); if(form.checkValidity()) { form.submit(); } else { // } } 

and then you just call this function when you want to start submitting the form.

+2
source

You do not need to use form.submit() ever. Do it right ( onsubmit ) or use click() in the submit button.

Performing this action ...

I can’t come up with a good reason for automatically representing the visible form. To send data without user use, use XMLHttpRequest or WebSockets .

The form is submitted through user interaction (for example, by clicking the submit button), so there is no need to use JavaScript to submit the form. Most likely, you need JavaScript to prevent form submission by returning false to the onsubmit event onsubmit .

... or use click()

To programmatically invoke HTML5 validation (as well as any onsubmit JavaScript event handlers attached to the form), you can invoke the click() function of the submit button that belongs to the form.

If the form does not have a submit button, you can create a temporary one:

 var form = document.getElementById("mc-embedded-subscribe-form"); var button = document.createElement('input'); button.type = 'submit'; button.style.display = 'none'; form.appendChild(button); button.click(); 

Forms with multiple submit buttons must have name attributes so that the server can determine which button the user clicked on. You can 'click' to use these buttons with form.buttonName.click() .

0
source

All Articles