Form validation in modal using Bootstrap

Asked

Viewed 5,016 times

11

I have the following question. I have a simple record and I want you to tell me when registering a new record:

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

  2. If the form field already exists in the database it shows that "Duplicate value";

  3. If there is not yet, he will save in the bank;

Good, but I wanted to do this modal check. 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>
  <script src="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>

PHP TEST.

<?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 check, it is possible to do the same with the modal?

  • 3

    you will need to use AJAX to be able to manipulate the data only by modal.

  • Yes the question is "the code". But they answered me on the American website. For those who need the same thing, it is really necessary to use Ajax, because it is not performed 'Submit' then it is necessary the following code:

  • <script> $('form'). Submit(Function() { $.post("test.php", {username: $(this)[0].username.value}, Function (d) { $('#myModal').find(".modal-body").html(d); $('#myModal').modal('show'); }); turn false; }); </script>

3 answers

1

if someone is still in need... something like this can be done, first cancel the form Ubmit with Event.preventDefault() then scans all inputs $.each() 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 be worked in 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 like magic, it analyzes the solution.

0

It can yes perfectly, simple :

  • form is out of modal and "Submit" opens modal
  • inserts a "loading of life" into the modal
  • and returns via AJAX the callback (Success) in the modal;

$(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
     }
   });


});

0

The best way to do this according to your code is through Javascript. From what I’ve noticed you’re using the jQuery, then validate whether the fields are empty or not is quite simple. For example:

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

Regarding the query in the database to verify that the value is not duplicated, da para fazer usando o método Ajax do próprio jQuery, onde você fazer um requição a arquivo PHP no servidor que executará uma query no banco de dados e retorno true ou false (em json) if the value already exists or not.

An example 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
});
  • Hi Victor, here we do not use signatures within the post, the question is only to expose the problem and the answer only to offer the solution. Our avatar below each question/answer is our signature. You can use your profile to put any type of link or personal promotion. Thanks!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.