problems when validating form

1

I have a form that sends information to another web page to do an operation on a DB, but I am trying to validate the form first so that it does not send empty fields to the DB, the validation I already have but I could not do to validate first and if there are no empty fields send the information to the BD, since it currently sends even when it is validated but it is because I have a js that has a click event where the form is processed through ajax to the other page and I do not know how to do it first validate and then process, doing tests, comment on the click function and validate you may have to occupy another event but I do not know, this is my code:

    $('#btnGuarda').click(function () {        
        
        var cargando = $("#carga").html("<center><img class='img-responsive'  src='../imagenes/loading.gif'/><center>");

        $.ajax({
            type: 'POST',
            url: '../statussol/procesaConfirmada.vbhtml',
            data: $('#enviaConfirmada').serialize(),
            beforeSend: function () {
                $("#muestraFormulario").hide();
                cargando.show().fadeIn();
            },
            success: function (e) {
                cargando.hide();                
                $('#resultado').hide().html("<blockquote style='background: #f9f9f9; border-left: 10px solid #ccc;   margin: 1.5em 10px;  padding: 0.5em 10px;'> <p></p><p style='color:green'><i class='glyphicon glyphicon-ok-circle'></i> ¡ Operación exitosa !</p><p></p> </blockquote>").fadeIn(500);
                $('#resultado').html(e);
            }
        });
    });
/* VALIDACION A MI INPUT DEL FOMULARIO*/
    $('#enviaConfirmada').bootstrapValidator({
        message: 'Este valor no es valido',
        feedbackIcons: {
            valid: 'glyphicon glyphicon-ok',
            invalid: 'glyphicon glyphicon-remove',
            validating: 'glyphicon glyphicon-refresh'
        },
        fields: {
            txtVendedor: {
                validators: {
                    notEmpty: {
                        message: 'El # de vendedor es requerido'
                    }
                }
            }
        }
    });
});

my form

<html xmlns="http://www.w3.org/1999/xhtml">

<head>
  <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
  <title></title>

  <link href="../css/bootstrap.min.css" rel="stylesheet" />
  <link href="../css/bootstrapValidator.min.css" rel="stylesheet" />

  <script type="text/javascript" src="../js/jquery-1.11.2.min.js"></script>
  <script type="text/javascript" src="../js/bootstrap.min.js"></script>
  <script type="text/javascript" src="../js/bootstrapValidator.min.js"></script>
  <script type="text/javascript" src="../js/scriptsConfirma.js"></script>
  <script src="../js/validate.js"></script>

</head>

<body>
  <!-- div muestra formulario -->
  <div id="muestraFormulario">
    <!-- formulario -->
    <div class="alert alert-info" role="alert"><i class="glyphicon glyphicon-asterisk"></i> Ingrese número</div>
    <form id="enviaConfirmada" name="enviaConfirmada" method="post" action="" class="form-horizontal">

      <div class="form-group">
        <label for="lblSolicitud" class="control-label col-sm-3">N° de solicitud</label>
        <div class='input-group col-sm-8'>
          <span class="input-group-addon">
                                            <span class="glyphicon glyphicon-info-sign"></span>
          </span>
          <input type='text' id="txtNumsolicitud" name="txtNumsolicitud" class="form-control" readonly="readonly" />
        </div>
        <label for="lblSolicitud" class="control-label col-sm-1"></label>
      </div>

      <div class="form-group">
        <label for="lblFecha" class="control-label col-sm-3">Fecha</label>
        <div class='input-group col-sm-8'>
          <span class="input-group-addon">
                                            <span class="glyphicon glyphicon-info-sign"></span>
          </span>
          <input type='text' id="txtFecha" name="txtfecha" class="form-control" readonly="readonly" />
        </div>
        <label for="lblFecha" class="control-label col-sm-1"></label>
      </div>
      <label class="col-md-3 control-label">N° de vendedor</label>

      <div class="col-md-7">
        <input type='text' id="txtVendedor" name="txtVendedor" maxlength="4" onkeypress="ponerMayusculas(this);" class="form-control" />
      </div>
      <div class="form-group">
        <label class="control-label col-sm-9"></label>
        <div class="col-sm-3">

          <button type="button" class="btn btn-success" id="btnGuarda">Guardar</button>
        </div>
      </div>
    </form>
    <!-- fin formulario -->
  </div>
  <!-- div muestra formulario -->
  <div id="carga"></div>
  <div id="resultado"></div>

</body>

</html>
    
asked by Drago25 22.03.2016 в 17:30
source

4 answers

1
  

I have a form that sends information to another website to do an operation

No. You do not have a form that sends information ... and that is the real problem in the code: the form is never sent and, therefore, never gets validated .

The validation plugin checks when the form has been sent, that is, when the submit event is launched. And that never happens because you are using a button of type button , so the form is not sent anywhere, instead it calls a function that reads the form data and sends it via AJAX (without doing submit ).

Two possible solutions to the problem:

1. Have the form sent

For this, what you should do is the following:

  • Change the button from type="button" to type="submit" . This way, the form will be sent when you click it.

    <button type="submit" class="btn btn-success" id="btnGuarda">Guardar</button>
    
  • Change the click driver and make it a separate function.

    function enviarFormulario() {   
    
        var cargando = $("#carga").html("<center><img class='img-responsive'  src='../imagenes/loading.gif'/><center>");
    
        $.ajax({
            type: 'POST',
            url: '../statussol/procesaConfirmada.vbhtml',
            data: $('#enviaConfirmada').serialize(),
            beforeSend: function () {
                $("#muestraFormulario").hide();
                cargando.show().fadeIn();
            },
            success: function (e) {
                cargando.hide();                
                $('#resultado').hide().html("<blockquote style='background: #f9f9f9; border-left: 10px solid #ccc;   margin: 1.5em 10px;  padding: 0.5em 10px;'> <p></p><p style='color:green'><i class='glyphicon glyphicon-ok-circle'></i> ¡ Operación exitosa !</p><p></p> </blockquote>").fadeIn(500);
                $('#resultado').html(e);
            }
        });
    }
    
  • Change the action of the form to point to the function in point 2.

    <form id="enviaConfirmada" name="enviaConfirmada" method="post" action="javascript:enviarFormulario()" class="form-horizontal">
    
  • Now that it is like this, when you press the button, the form will be sent, but first the validation of the jQuery plugin will occur and only if it is validated will the new function you created in step 2 be called.

    2. Delegate the submission to the plugin

    If you go to the plugin documentation, you can see that there are several examples that They show how to do what you want. For this, what you should do is add another controller when you create the bootstrapValidator.

    It would be something like that (I have not checked it, it may contain errors):

     $('#enviaConfirmada').bootstrapValidator({
    
         // tu código aquí, no hay necesidad de cambiar nada
    
     })
     .on('success.form.bv', function(e) {
            // Prevén que se mande el formulario
            e.preventDefault();
            // Obtén el formulario
            var $form = $(e.target);
            // Obtén la instancia de bootstrapValidator
            var bv = $form.data('bootstrapValidator');
            // Usa AJAX para enviar el formulario como lo estabas haciendo
            $.post(
                '../statussol/procesaConfirmada.vbhtml', 
                $form.serialize(), 
                function(result) {
                    console.log(result);
                }, 
                'json'
             );
        });+
    
      

    NOTE- As a personal recommendation: stop using that jQuery plugin (or update to the latest version). If you go to the project page on GitHub , you will see that the project is no longer supported and recommend using FormValidation instead.

        
    answered by 23.03.2016 / 00:16
    source
    1

    You can try using jquery.validate.js

    $(document).ready(function(){
        var form = $('#enviaConfirmada');
        form.validate({
            rules:{
                txtNumsolicitud: {
                        required: true, // hay más reglas aplicables
                        maxlength: 10
                    }
                },
                otroCampo:{
                        // reglas
                    }
                }
        });
    
        $('#btnGuarda').click(function () {        
            var cargando = $("#carga").html("<center><img class='img-responsive'  src='../imagenes/loading.gif'/><center>");
            if(form.valid()){
                // logica ajax
            }
        });
    });
    
        
    answered by 22.03.2016 в 21:48
    1

    You try to put all your inputs attribute required .

    Example:

    <form action="demo_form.asp">
      Username: <input type="text" name="usrname" required>
      <input type="submit">
    </form> 
    

    You can also validate the blank fields before serializing the form and send it by ajax:

    $('#btnGuarda').click(function () { 
     $("#enviaConfirmada").find("input").each(function(){
      if($(this).val() == ""){
       alert('Faltan campos por llenar');
       return false;
      }
     });
     var cargando = $("#carga").html("<center><img class='img-responsive'  src='../imagenes/loading.gif'/><center>");
    
     $.ajax({
      type: 'POST',
      url: '../statussol/procesaConfirmada.vbhtml',
      data: $('#enviaConfirmada').serialize(),
      beforeSend: function () {    
    ...
    ...
    
        
    answered by 22.03.2016 в 20:17
    0

    <script>
    $(document).ready(function() {
        $('#loginForm').bootstrapValidator({
            message: 'This value is not valid',
            feedbackIcons: {
                valid: 'glyphicon glyphicon-ok',
                invalid: 'glyphicon glyphicon-remove',
                validating: 'glyphicon glyphicon-refresh'
            },
            submitHandler: function(validator, form, submitButton) {
                $.post(form.attr('action'), form.serialize(), function(result) {
                    // The result is a JSON formatted by your back-end
                    // I assume the format is as following:
                    //  {
                    //      valid: true,          // false if the account is not found
                    //      username: 'Username', // null if the account is not found
                    //  }
                    if (result.valid == true || result.valid == 'true') {
                        // You can reload the current location
                        window.location.reload();
    
                        // Or use Javascript to update your page, such as showing the account name
                        // $('#welcome').html('Hello ' + result.username);
                    } else {
                        // The account is not found
                        // Show the errors
                        $('#errors').html('The account is not found').removeClass('hide');
    
                        // Enable the submit buttons
                        $('#loginForm').bootstrapValidator('disableSubmitButtons', false);
                    }
                }, 'json');
            },
            fields: {
                username: {
                    validators: {
                        notEmpty: {
                            message: 'The username is required'
                        }
                    }
                },
                password: {
                    validators: {
                        notEmpty: {
                            message: 'The password is required'
                        }
                    }
                }
            }
        });
    });
    </script>

    Source: link

        
    answered by 22.03.2016 в 21:27