I have a form and in this I have two INPUTS , these are mandatory so I use the HTML5 REQUIRED property but it only works if I place a BUTTON and this makes my page reload when submitting but I don't send it directly but I use Ajax , and since I want to validate them for that I have used:
<form>
<input type="text" id="dato1" required>
<input type="text" id="dato2" required>
<input type="button" id="boton" value="enviar" onclick="mifuncion()">
</form>
but this does not validate the form with HTML5 using REQUIRED if I use BUTTON the page is reloaded and I lose the information loaded with AJAX
<button onclick="mifuncion()">Enviar </button>
What I want to achieve is the validation that I have the BUTTON but that the page is not reloaded
Good evening, if what you are looking for is that when you press the button your ajax is executed instead of the submit of the form, you must override the submit function using ajax:
To send a form by AJAX, first of all, the default action must be prevented (sending with document reload). This is done using the function
preventDefault
.Event
This method prevents the default action from being performed on an event so you can customize this behavior.HTML5 also proposes you to use custom validations through the attribute
pattern
which accepts regular expressions and if you want to programmatically validate a form, you can use the functioncheckValidity
for each control.You could do it using:
event.preventDefault()
: Cancels the event if it is cancelable, without stopping the rest of the event's operation, that is, it can be called again.element.checkValidity()
: Method checks if the element has constraints and if it satisfies them.Modifications:
To be able to use
preventDefault
, the functionmifuncion
must receive the object as a parameterevent
. When assigning the function in the eventonclick
ofbutton
, you have to pass it. Example:To check if the
form
is valid or not, you have to useform.checkValidity()
.demonstration:
As it was named before, what you have to do is that when submitting the form,
submit
stop the submit event and analyze the fields, according to your requirement.Cheers,