How to validate a field in html5 without reloading the page?

7

I have a form and in this I have two INPUTS , these are required so I use the HTML5 REQUIRED property but it only works if I put a BUTTON strong> and this makes my page recharge when doing submit but I do not send it directly but I use Ajax , and then I want to validate them for that I 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 I do not recharge the page

    
asked by Paulker 10.02.2017 в 03:33
source

4 answers

7

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 overwrite the function of submit via ajax:

<script type="text/javascript">
    $(document).ready(function () {
        $("#boton").submit(function (event) {

            // Aqui evitamos que el formulario haga el submit
            event.preventDefault();

            // Get Asignamos valores para enviarlos mediante ajax:

            var posting = $.post('source/login.php', {
                user: $("#inputEmail").val(), // valor de input, aqui puedes hacer tus validaciones
                pass: $("#inputPassword").val()
            });
            posting.done(function (data) {
                if (data == "Success") { // Respuesta de tu archivo php
                    window.location.href = "menu.php";
                }
                else {
                    alert("El usuario o contrasena es incorrecto");
                    location.reload();
                }
            });
        });

    });
</script>
    
answered by 10.02.2017 / 03:39
source
4

To send a form via AJAX, first prevent the default action (sending with document reload). This is done using the preventDefault Event . This method prevents the default action that is performed in an event to customize this behavior.

$('form').on('submit', function (e) {
  e.preventDefault(); // se previene la acción por defecto
  
  // realizar petición AJAX
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
   <input type="text" id="dato1" required>
   <input type="text" id="dato2" required>
   <input type="submit" id="boton" value="enviar">
</form>

HTML5 also proposes you to use custom validations using the pattern attribute. which accepts regular expressions and if you want to validate a form programmatically, you can use the function checkValidity for each control.

    
answered by 10.02.2017 в 04:01
4

You could do it using:

  • event.preventDefault() : Cancels the event if it is cancelable, without stopping the rest of the operation of the event, that is, it can be called again.

  • element.checkValidity() : Method checks if the element has restrictions and if it satisfies them.

Modifications:

  • To be able to use preventDefault , the function mifuncion must receive by parameter the object event . When assigning the function in the event onclick of button , you have to pass it. Example:

    onclick="mifuncion(event)"
    
  • To check if the form is valid, or not, you have to use form.checkValidity() .

Demo:

var form = document.getElementById('form');
function mifuncion(event) {
  // Evitamos que el formulario se envíe
  event.preventDefault();
  
  // Si el form no es valido
  if (!form.checkValidity()) {
    console.log('Nop');
    return false;
  }
  
  console.log('Sip');
  // Tu código AJAX!
}
<form id="form">
  <input type="text" id="dato1" required>
  <input type="text" id="dato2" required>
  <button onclick="mifuncion(event)">Enviar</button>
</form>
    
answered by 10.02.2017 в 14:48
1

As you mentioned before, what you should do is that when you send the form submit stops the sending event and analyzes the fields, according to your requirement.

<script type="text/javascript">
jQuery(document).ready(function(){
    jQuery('#formulario').on('submit', function (e) {
       e.preventDefault();

       var dataForm = jQuery(this).serializeArray();
       // Valida los Campos

       // Envía por ajax el formulario
       var request = jQuery.ajax({
         url: '/url/',
         type: 'POST',
         dataType: 'json',
         data: dataForm
       });

       request.done(function (response) {
         console.log('done');
       });

       request.fail(function (jqXHR, textStatus) {
         console.log('error');
       });
     });
});
</script>

Greetings,

    
answered by 10.02.2017 в 04:01