How to "validate" input

3

I'm looking for a method to check if the input's required with the page are valid every time I click the save button, but I'm trying to do this without having to check one by one, below what I've done.

I had to leave the button as "type = 'button'" because of some functions that I have to add in the future.

HTML:

<body>
<form>
    <div>
        <label for="last_name">Date</label>
        <input type="text" name="date" id="date" required onfocus="(this.type='date')" placeholder="dd / mm / aaaa" onblur="(this.type='text')">
    </div>
    <div>
        <label>Email</label>
        <input type="email" required name="email" id="email" placeholder=" ">
    </div>
    <div>
        <label>CEP</label>
        <input type="text" name="cep" id="cep" required placeholder=" " pattern="\d{2}\.\d{3}-?\d{3}">
    </div>
    <div>
        <label>CPF</label>
        <input type="text" name="cpf" id="cpf" required placeholder=" " pattern="\d{3}\.\d{3}\.\d{3}-\d{2}" maxlength="14">
    </div>
    <div>
        <label>RG</label>
        <input type="text" name="rg" id="rg" required placeholder=" " pattern="\d{2}\.\d{3}\.\d{3}-\d{1}" maxlength="12">
    </div>
    <div>
        <label>CNPJ</label>
        <input type="text" name="cnpj" id="cnpj" required placeholder=" " pattern="[0-9]{2}[\.]?[0-9]{3}[\.]?[0-9]{3}[\/]?[0-9]{4}[-]?[0-9]{2}">
    </div>
    <div>
        <label>Telefone Residencial</label>
        <input type="text" name="telefone" id="telefone" required placeholder=" " pattern="[\(]\d{2}[\)][\s]\d{4}[\-]\d{4}">
    </div>
    <div>
        <label>Telefone Celular</label>
        <input type="text" name="cel" id="cel" required placeholder=" " pattern="[\(]\d{2}[\)][\s]\d{1}[\s]\d{4}[\-]\d{4}">
    </div>
    <button type="button" id="salve">salvar</button>
</form>
</body>
<script src="js/jquery.js"></script>
<script src="https://igorescobar.github.io/jQuery-Mask-Plugin/js/jquery.mask.min.js"></script><scriptsrc="js/mascara.js"></script>

CSS:

input[type="text"]:invalid:not(:focus):not(:placeholder-shown),
input[type="date"]:invalid:not(:focus):not(:placeholder-shown),
input[type="email"]:invalid:not(:focus):not(:placeholder-shown){
    border-color:red;
    border-width: 3px;
}
input:valid {
    border-color:green;
    border-width: 3px;
}

JS:

$("#value").mask("#.##0,00", { reverse: true });
$("#telefone").mask("(00) 0000-0000");
$("#cel").mask("(00) 0 0000-0000");
$("#cpf").mask("#00.000.000-00", { reverse: true });
$("#rg").mask("#0.000.000-0", { reverse: true });
$("#cep").mask("00.000-000");
$("#cnpj").mask("00.000.000/0000-00");

var salve = $("#salve");
salve.on("click", function() {

//verificar se os inputs estão vazios
var vazios = $("input").filter(function() {
    return !this.value;
}).get();

console.log(vazios);

if (vazios.length) {
    $(vazios).addClass('vazio');
    console.log("Todos os campos devem ser preenchidos.");
    return false;
}else {
    console.log("Eureka");
}

// tentativa de verificar se os inputs estão validos
var validos = $("input").filter(function() {
    return this.valid;
}).get();
console.log(validos);
});

In case I put a visual validation on the inputs and I was able to check if the inputs are empty, I just can not validate if they are filled correctly

    
asked by anonymous 27.04.2018 / 16:48

2 answers

2

The error is in the return of filter . You should check the element with the pseudo-class :valid this way, using the .is method:

var validos = $("input").filter(function() {
       return $(this).is(":valid"); // valida o campo. Retorna true ou false
   }).get();
});
    
27.04.2018 / 17:54
0

You can create a function that calls in the subumit so you can return a message, change the border color of the css or something else you want:

    function validaDados() {
            var mensagem = "";
            //Guia Geral
            if ($("#input1").val() == null || $("#representante").val() == "") {
                $("#input1").css({ "border-color": "#F00", "padding": "1px" });
                $("#errorinput1").html("é obrigatório");
                mensagem = "1";
            } else {
                $("#input1").css({ "border-color": "blue", "padding": "1px" });
                $("#errorinput1").html("");
            }

            if (mensagem != "")//se a variavel mensagem tiver  conteudo,ou seja ,se tiver ocorrido ,algum erro no preenchimento
            {
                $("#resposta").addClass("alert alert-danger");
                $('#resposta').html('Verifique o formulário, existem campos obrigatórios não preenchidos');
                $('#resposta').show(); //MOSTRA A DIV DE RESPOSTA
                return false;
            } else { // se não
                $('#resposta').html('');
                $('#resposta').hide();

                return true;
            }
        }
    
11.05.2018 / 19:32