How to "validate" the input

Asked

Viewed 598 times

3

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

BS: I had to leave the button as "type='button'" because of some functions I will 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>
<script src="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 in the inputs and I was able to verify that the inputs are empty, I’m just not able to validate if they are filled correctly

  • Wouldn’t you be able to use JS to identify if the inputs received the css "input:Valid" and check from it? That’s kind of what I was trying to do

2 answers

2


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

var validos = $("input").filter(function() {
       return $(this).is(":valid"); // valida o campo. Retorna true ou false
   }).get();
});
  • Thanks for the help, it worked perfectly!

0

You can create a function that calls in subumit so you can return message, change the color of the css border, or anything 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;
            }
        }

Browser other questions tagged

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