Validate data and display bootstrap alerts

1

I have done a bootstrap form in a modal, that when I give a submit button "save", I save the values of the fields in the database. So far so good.

I would like that before sending the values, the fields will be validated, to see if a field is empty or there is something that does not want to put, as an age in negative.

I have understood that all people use jquery but for me it is a mess of the ciborium, but if you have to do it that way, go ahead. Well, nothing, I ask you as something that the fields are validated and that those alerts come out above the modal so pretty bootstrap.

Here I leave my form

        <div class="modal" id="nuevoUsu" tabindex="-1" role="dialog" aria-labellebdy="myModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
                    <h4>Nuevo Contacto</h4>                       
                </div>
                <div class="modal-body">
                   <form action="insertar.php" method="GET">                    
                        <div class="form-group">
                            <label for="nombre">Nombre:</label>
                            <input class="form-control" id="nombre" name="nombre" type="text" placeholder="Nombre"></input>
                        </div>
                        <div class="form-group">
                            <label for="edad">Edad:</label>
                            <input class="form-control" id="edad" name="edad" type="text" placeholder="Edad"></input>
                        </div>
                        <div class="form-group">
                            <label for="direccion">Direccion:</label>
                            <input class="form-control" id="direccion" name="direccion" type="text" placeholder="Direccion"></input>
                        </div>

                        <input type="submit" class="btn btn-success" value="Salvar">
                   </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-warning" data-dismiss="modal">Cerrar</button>
                </div>
            </div>
        </div>
    </div> 

Sorry if I offended someone because of my poor ability to program, but at my age it is already difficult to learn.

    
asked by Vidal 19.03.2018 в 14:02
source

3 answers

5

First to validate that only numbers are entered you can do the following with javascript, it is used directly in the old input like this

 function solonumeros(e)
                    {
         var key = window.event ? e.which : e.keyCode;
                        if(key < 48 || key > 57)
                            e.preventDefault();
                    }
<label>Edad</label>
<input id="edad" type="text" onkeypress="solonumeros(event);">

That code does not allow you to enter other characters and letters. Then to validate afterwards you just have to ask if the input is less than 0 in this way, besides validating the other fields:

function validaCampos(){

var nombre = $("#nombre").val();
var edad = $("#edad").val();
var direccion = $("#direccion").val();
//validamos campos
if($.trim(nombre) == ""){
toastr.error("No ha ingresado Nombre","Aviso!");
    return false;
}
                   if($.trim(edad) == ""){
toastr.error("No ha ingresado Edad","Aviso!");
    return false;
}

            if(edad < 0){
toastr.error("Mínimo permitido 0","Aviso!");
    return false;
}
if($.trim(direccion) == ""){
toastr.error("No ha ingresado Dirección","Aviso!");
    return false;
}

}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
<link href="//cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/toastr.min.css" rel="stylesheet" >
<script src="//cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/toastr.min.js"></script>
<script>

//importamos configuraciones de toastr
toastr.options = {
  "closeButton": false,
  "debug": false,
  "newestOnTop": false,
  "progressBar": false,
  "positionClass": "toast-top-right",
  "preventDuplicates": false,
  "onclick": null,
  "showDuration": "300",
  "hideDuration": "1000",
  "timeOut": "5000",
  "extendedTimeOut": "1000",
  "showEasing": "swing",
  "hideEasing": "linear",
  "showMethod": "fadeIn",
  "hideMethod": "fadeOut"
}


</script>
<form action="insertar.php" method="GET" onsubmit="return validaCampos();">                    
                        <div class="form-group">
                            <label for="nombre">Nombre:</label>
                            <input class="form-control" id="nombre" name="nombre" type="text" placeholder="Nombre"></input>
                        </div>
                        <div class="form-group">
                            <label for="edad">Edad:</label>
                            <input class="form-control" id="edad" name="edad" type="text" placeholder="Edad"></input>
                        </div>
                        <div class="form-group">
                            <label for="direccion">Direccion:</label>
                            <input class="form-control" id="direccion" name="direccion" type="text" placeholder="Direccion"></input>
                        </div>

                        <input type="submit" class="btn btn-success" value="Salvar">
                   </form>

With this code you can validate before sending, then explain what the previous validation is about
when I say $.trim(nombre) in this line $.trim removes all the spaces within the field so even if you press the spacer key and send, it will validate that the input is blank. Then when I return false I do not send the form until the whole is correct. Finally I made use of the messages that the toastr library delivers, which is to show validation messages in a more graphic way. I hope you serve. Greetings.

  

NOTE: $ .trim () is from jquery, so you need that library to be able to   use it.

    
answered by 19.03.2018 / 15:01
source
1

I think your best option is to use bootstrapValidator ( link )

It uses jQuery, so you'll have to include it, but it's an easy and elegant solution.

You simply have to define in each field (identified by the name attribute) the rules that you want them to comply with. It also allows you to use custom rules.

$(document).ready(function() {
$('#nuevoUsu').modal() ;

$('#nuevoUsu').bootstrapValidator({            
        fields: {
           nombre: {
                validators: {
                    notEmpty: {
                        message: 'El nombre es obligatorio'
                    }
                }
            },
            edad: {
                validators: {
                    notEmpty: {
                        message: 'La edad es obligatoria'
                    },
                    integer: {
                    message: 'Debe introducir un valor entero'
                }
                }
            },
            direccion: {
                validators: {
                    notEmpty: {
                        message: 'La dirección es obligatoria'
                    }
                }
            }
        }
    });
});
<link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-validator/0.5.3/css/bootstrapValidator.min.css" rel="stylesheet"/>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"
integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-validator/0.5.3/js/bootstrapValidator.js"></script>

<div class="modal" id="nuevoUsu" tabindex="-1" role="dialog" aria-labellebdy="myModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
                    <h4>Nuevo Contacto</h4>                       
                </div>
                <div class="modal-body">
                   <form action="insertar.php" method="GET">                    
                        <div class="form-group">
                            <label for="nombre">Nombre:</label>
                            <input class="form-control" id="nombre" name="nombre" type="text" placeholder="Nombre"></input>
                        </div>
                        <div class="form-group">
                            <label for="edad">Edad:</label>
                            <input class="form-control" id="edad" name="edad" type="text" placeholder="Edad"></input>
                        </div>
                        <div class="form-group">
                            <label for="direccion">Direccion:</label>
                            <input class="form-control" id="direccion" name="direccion" type="text" placeholder="Direccion"></input>
                        </div>

                        <input type="submit" class="btn btn-success" value="Salvar">
                   </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-warning" data-dismiss="modal">Cerrar</button>
                </div>
            </div>
        </div>
    </div>

Here is a list of validations: link

    
answered by 19.03.2018 в 15:17
1

After looking for a bit I found this plugin, the validator for Bootstrap, easy to implement although it depends on jquery ... attached example of code so you can examine it ...

link

    
answered by 20.03.2018 в 17:13