Activate HTML5 validations from Js

2

I have this js, and this html:

$(document).on('click', '.validar', function (event) {
        event.preventDefault();
        var cantidad = 0;

        var obj = {
            "correo": $(".txtEmail").attr("id")
        };
        $.each(obj, function (identificador, value) {
            cantidad = ($.onlyData("#" + value));
            if (cantidad > 0) {
                toastr["error"]("Este " + identificador + " ya se encuentra registrado!");
            } else {
                $("#msform").submit();
            }
        });
    });
<div class="modal fade" id="modalNewClient" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
    <div class="modal-content">
        <div class="modal-header">
            <h5 class="modal-title" id="exampleModalLabel">Nuevo cliente</h5>
            <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                <span aria-hidden="true">&times;</span>
            </button>
        </div>
        <div class="modal-body">
            <?php
            echo $this->Form->create('Client', array('class' => '', 'id' => 'msform'));
            ?>
            <div class="input-group">
                <?php
                echo $this->Form->input('contact', array('label' => array('text' => " "),
                    'placeholder' => 'Danos tu nombre', 
                    "required" => "true", 
                    "minlength" => "5", 
                    "maxlength" => "", 
                    'class' => 'form-control-custom color-input validLength txtContact lang prettyName', 
                    'key' => 'txtContact'));
                ?>
            </div>
            <div class="input-group">
                <?php
                echo $this->Form->input('company', array('label' => array('text' => " "),
                    'placeholder' => '¿Para que marca vamos a trabajar?', "required" => "true", 
                    "minlength" => "3", 
                    "maxlength" => "",
                    'data-sql' => "company-Client",
                    'class' => 'form-control-custom color-input validLength txtClient lang prettyName', 
                    'key' => 'txtClient'));
                ?>
            </div>
            <div class="input-group mb-3">
                <?php
                echo $this->Form->input('email', array('label' => array('text' => " "),
                    'placeholder' => 'Correo electronico', 
                    "data-DB" => "email", 
                    "required" => "true", 
                    "minlength" => "5", 
                    'data-sql' => "username-User",
                    "maxlength" => "", 
                    'class' => 'form-control-custom color-input validLength prettyName txtEmail lang validEmail', 
                    'key' => 'txtEmail'));
                ?>
            </div>
            <div class="input-group mb-3">
                <?php
                echo $this->Form->input('phone', array('label' => array('text' => " "),
                    'placeholder' => 'Celular', "minlength" => "7", "required" => "true", "maxlength" => "10", 'class' => 'form-control-custom color-input validLength txtPhone blockLetter lang', 'key' => 'txtPhone'));
                ?>
            </div>
            <?php echo $this->Form->end(array('label' => 'Guardar cliente', 'class' => 'validar')) ?>
        </div>
    </div>
</div>

the thing is that that js, validates if a field already exists in the database, but I do not know if there is any way to activate, the automatic validations of html5 from the js, on the internet I found this: $("#elemento").checkValidity(); but it did not work, I was thinking about something $("#formId").checkRequired(); or something like that, but I could not find anything

those are the validations of html5 and what I want is to activate them from jquery that is to say with some function to tell you to do the validations that normally hacel the html5 when giving a submit

    
asked by Andrés Vélez 20.06.2018 в 23:45
source

2 answers

3

The question is still very broad, you need to give us more information such as when you want the review to be done or how you want it to run ... with a button without submit, when typing, when leaving the field, etc. ...

As a note checkValidity() is a JavaScript method, not jQuery. So if you want to use it in a jQuery object you should use $("#MiForma")[0].checkValidity()

But since in your question you only ask for a function that validates the fields you can try this:

function validar (){
    var forma = document.getElementById("MiForma");
  if(forma.checkValidity()){
    console.log("Forma Válida");
    $("#MiForma").submit();
  }else{
  $("#enviar").click()
    console.log("Forma invalida, deberían salir mensajes html5");
}}
    
answered by 21.06.2018 / 19:46
source
0

Friend depends on the validation you want to make, for example if you want an input to be required, then you can use the following:

document.getElementById("txtinput1").attributes["required"] = "";  

this in javascript, so I think it should be more specific in the matter, but in this way you can do it. You can do a validation as indicated in the update, but it would not stay the same as the validation of html5 with the floating bubble, if not you would have a red box in the field or green, and a message below, I will add documentation about this : from the html side the following (in the form you call a javascript function with the event onsubmit or you call the function in the event onkeyup ):

<form action="/action_page.php" onsubmit="return myFunction()">
  Campo ingresar:<br>
  <input type="email" name="correo" placeholder="[email protected]" onkeyup="myFunction()">
  <div id="salida" style="color: red;"></div>
  <br>
  <br><br>
  <input type="submit" value="Submit">
</form> 

in javascript the following:

function mifunction(){
event.preventDefault();
        var cantidad = 0;
        var verificado= true;

        var obj = {
            "correo": $(".txtEmail").attr("id")
        };
        $.each(obj, function (identificador, value) {
            cantidad = ($.onlyData("#" + value));
            if (cantidad > 0) {
                document.getElementById("correo").style.borderColor = "#b03535";//esto pone color rojo el campo
                document.getElementById("salida").innerHTML = ("Ya se encuentra registrado"); //esto muestra un mensaje en el div salida
                verificador=false; //esto evita que el formulario se envie
            } 
        });
if (verificador==false){
    return false;
}
}
    
answered by 21.06.2018 в 01:01