Modal form validation using Bootstrap

11

I have the following question. I have a simple registry and I want to register a new registry and tell me:

  • If the field is empty it shows me the message "Fill in the fields";

  • If the form field already exists in the database it shows "Duplicate Value";

  • If it does not already exist, it will save to the bank;

  • Well, but I wanted to do this check in modal. I did the following tests:

    INDEX.PHP

    <html>
    
    <title>Modal</title>
    <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
    <head>
    
      <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script><scriptsrc="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
      <style>
      .modal-header, h4, .close {
          background-color: #5cb85c;
          color:white !important;
          text-align: center;
          font-size: 30px;
      }
      .modal-footer {
          background-color: #f9f9f9;
      }
      </style>
    </head>
    <body>
    
    <form action="teste.php" method="post">
        Nome:  <input type="text" name="username" > <input type="submit" name="submit" value="Abrir sem modal" />
    
    <div class="container">
      <button type="button" class="btn btn-info btn-lg" data-toggle="modal" data-target="#myModal">Abrir com modal</button>
      <div class="modal fade" id="myModal" role="dialog">
        <div class="modal-dialog">
          <div class="modal-content">
            <div class="modal-header">
              <button type="button" class="close" data-dismiss="modal">&times;</button>
              <h4 class="modal-title">Teste Modal</h4>
            </div>
            <div class="modal-body">
              <p><?php include 'teste.php'; ?></p>
            </div>
            <div class="modal-footer">
              <button type="button" class="btn btn-default" data-dismiss="modal">Fechar</button>
            </div>
          </div>
        </div>
      </div>
    </div>
    
    </form>
    
    </body>
    </html>
    

    TEST.PHP

    <?php
    
    require("conexao.php");
    
            $nome = $_POST['username'];
    
            if ($nome == "")  {
                echo "Preencha o campo";
            } else {
                $sql = mysql_query("SELECT nome FROM tb_visitas WHERE nome='$nome'");
    
                if (mysql_num_rows($sql) > 0) {
                    echo "Valor duplicado";
                } else {
                    echo "Gravando registro";
                }
            }   
    ?>
    

    On the "no modal" button it does the correct verification, is it possible to do the same with the modal?

        
    asked by anonymous 21.09.2015 / 20:11

    3 answers

    1

    If someone is still in need ... something like this can be done, first cancels the form submit with event.preventDefault () then scans all $. () to check if they are filled, and finally the $ .ajax call working the return.

    <script>
    var form = $('.form-validation')[0];
    if(form != undefined){
        form.addEventListener('submit', function(event) {
                if (!event.target.checkValidity()) {
                    event.preventDefault();
                    $('.form-validation [required]').each(function(i, o){
                        if(!$(o).val().length){
                            $(o).addClass('input-error');
                        } else {
                            $(o).removeClass('input-error');
                        }
                    });
                    if($('.input-error').length == 0){
                        $.ajax({
                            type: 'post',
                            url: 'teste.php's,
                            data: $('.form-validation').serialize(),
                            contentType: 'application/x-www-form-urlencoded',
                            success: function(response) {
                                if(response.status == 'salvo') {
                                    alert('salvo');
                                } else if (response.status == 'duplicado'){
                                    alert('duplicado');
                                }
                            },
                            error: function(xhr, error) {
                                alert(error);
                            }
                        })
                    }
                }
            }, false);
    </script>
    

    and in the .php file you have to return a json, to work on the response parameter

    <?php
        $sql = mysql_query("SELECT nome FROM tb_visitas WHERE nome='{$_POST['nome']}'");
    
        if (mysql_num_rows($sql) > 0) {
            echo json_encode(array('status'=>'duplicado'));
        } else {
            //SQL INSERT INTO tb_visitas
            echo json_encode(array('status'=>'salvo'));
        }
     ?>
    

    Of course, it's not just because the code will work as magic, it does an analysis of the solution.

        
    25.10.2015 / 01:09
    0

    Yes, it is perfectly simple:

    • the form is out of modal and "submit" opens the modal
    • inserts a "loading of life" in the modal
    • and return via modal callback (AJAX);

    $(function(){
    
       $.ajax({
         url : 'update.php',
         type : 'POST',
         data : info_do_formulario,
         beforeSend : function(){
           // insere algum loading dentro do modal
           $('#myModal').modal('show'); // abre o modal
         },
         success : function(data){
           // substitui o loading pelo callback 'data', com a sua resposta específica
         }
       });
    
    
    });
        
    18.11.2015 / 07:16
    0

    The best way to do this according to your code is through JavaScript. From what I realize you're using jQuery , then validate whether the fields are empty or not very simple. For example:

    if ($('#username').val() != '') {
      alert('campo preenchido');
    } else {
      alert('campo vazio');
    }
    

    Regarding the query in the database to check if the value is not duplicated, you can do it using jQuery's own Ajax method, where you will make a request to a PHP file on the server that will execute a query in the database and return true or false (in json) if the value already exists or not.

    In an exemplified way it would be the following:

    $.ajax({
      url: 'http://dominio.com/arquivo.php', // arquivo PHP que consultará o BD
      data: {'username':$('#username').val()}, // conteúdo do campo username
      success: function(resultado) {
        // verificando o json que retornou
        if (resultado.status == true) {
          alert('nome válido');
        } else {
          alert('nome duplicado');
        }
      },
      dataType: json
    });
    
        
    01.10.2015 / 18:07