How to change the color of the input using jquery Validate?

Asked

Viewed 3,050 times

4

I am implementing a jquery form, and I want that when Valida runs and class error is added to the label leaving the red font, I will send a picture representing how I want.

<html>
    <head>
        <title>Como Validar um Formulário dinamicamente com jQuery</title>        
        <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js" ></script>           
        <script type="text/javascript">
            $(function () {
                
                $("#my-form").validate({
                    focusCleanup: true,
                    errorLabelContainer: "input .labell",
                    errorElement: "div",
                    rules: {
                        nome: {
                            minlength: 3,
                            maxlength: 50
                        },
                        empresa: {
                            minlength: 4
                        }
                    },
                    messages: {
                        nome: {
                            required: "",
                            minlength: "Insira seu nome completo!"
                        },
                        cpf: {
                            required: ""
                        },
                        empresa: {
                            required: "",
                            minlength: "Preencha no mínimo 4 caracteres!"
                        }
                    }
                });
            });
        </script>
    </head>
    <body class="container">
        <form class="text-uppercase" role="form" id="my-form" method="post" action="add_pess.php"><br><br>
            <div class="row">
                <div class="col-md-12">
                    <label class="labell" id="lb_nome" for="nome">Nome Completo:</label>                                  
                    <input type="text" class="form-control required" id="nome" name="nome" placeholder="Digite seu nome completo">
                </div>
            </div><br>
            <div class="row">
                <div class="col-md-12">
                    <label id="lb_cpf" class="labell" for="cpf">CPF:</label>
                    <input type="tel" class="form-control required" id="cpf" name="cpf" placeholder="Digite o CPF">
                </div>
            </div><br>  
            <div class="row">
                <div class="col-md-12">
                    <label id="lb_empresa" class="labell" for="empresa">Empresa:</label>                 
                    <input type="text" class="form-control required" id="empresa" name="empresa" placeholder="Digite o nome da empresa">
                </div>
            </div><br>
            <div class="row">                          
                <div class="col-md-12">
                    <label>Relacionamento:</label>            
                    <select name="tipo" id="tipo" class="form-control">
                        <option value="CLIENTE">CLIENTE</option>
                        <option value="FORNECEDOR">FORNECEDOR</option>
                        <option value="PARCEIRO">PARCEIRO</option>
                        <option value="OUTRO">OUTRO</option>
                    </select>
                </div>                 
            </div><br>
            <div class="row">
                <div class="col-md-12">
                    <label for="ob">Observações:</label>                 
                    <textarea rows="5" class="form-control" id="ob" name="ob" placeholder="Se caso haver alguma observação digite aqui"></textarea>
                </div>
            </div><br>
            <div class="text-right col-md-12">
                <button id="submit" type="submit" class="btn btn-primary">Enviar</button>
            </div><br>
        </form> 
        <script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.15.0/jquery.validate.js"></script>
        <script type="text/javascript" src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" ></script>
    </body>
</html>

inserir a descrição da imagem aqui

  • Your code is giving error when executing. Could fix it?

  • { "message": "Uncaught Syntaxerror: Unexpected token <", "filename": "http://stacksnippets.net/js", "lineno": 38, "colno": 9 }

  • Yes I’ll fix it.

3 answers

6

Just use the callbacks highlight and unhighlight:

<html>
    <head>
        <title>Como Validar um Formulário dinamicamente com jQuery</title>        
        <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js" ></script>
        <script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.15.0/jquery.validate.js"></script>
        <script type="text/javascript" src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" ></script>           
        <script type="text/javascript">
            $(function () {
                
                $("#my-form").validate({
                    highlight: function(element) {
                        $(element).parent().parent().addClass('has-error');
                    },
                    unhighlight: function(element) {
                        $(element).parent().parent().removeClass('has-error');
                    },
                    focusCleanup: true,
                    errorLabelContainer: "input .labell",
                    errorElement: "div",
                    rules: {
                        nome: {
                            minlength: 3,
                            maxlength: 50
                        },
                        empresa: {
                            minlength: 4
                        }
                    },
                    messages: {
                        nome: {
                            required: "",
                            minlength: "Insira seu nome completo!"
                        },
                        cpf: {
                            required: ""
                        },
                        empresa: {
                            required: "",
                            minlength: "Preencha no mínimo 4 caracteres!"
                        }
                    }
                });
            });
        </script>
    </head>
    <body class="container">
        <form class="text-uppercase" role="form" id="my-form" method="post" action="add_pess.php"><br><br>
            <div class="row">
              <div class="form-group">
                <div class="col-md-12">
                    <label class="labell" id="lb_nome" for="nome">Nome Completo:</label>                                  
                    <input type="text" class="form-control required" id="nome" name="nome" placeholder="Digite seu nome completo">
                </div>
              </div>
            </div>
            <div class="row">
              <div class="form-group">
                <div class="col-md-12">
                    <label id="lb_cpf" class="labell" for="cpf">CPF:</label>
                    <input type="tel" class="form-control required" id="cpf" name="cpf" placeholder="Digite o CPF">
                </div>
              </div>
            </div>
            <div class="row">
              <div class="form-group">
                <div class="col-md-12">
                    <label id="lb_empresa" class="labell" for="empresa">Empresa:</label>                 
                    <input type="text" class="form-control required" id="empresa" name="empresa" placeholder="Digite o nome da empresa">
                </div>
              </div>
            </div>
            <div class="row">     
              <div class="form-group">                     
                <div class="col-md-12">
                    <label>Relacionamento:</label>            
                    <select name="tipo" id="tipo" class="form-control">
                        <option value="CLIENTE">CLIENTE</option>
                        <option value="FORNECEDOR">FORNECEDOR</option>
                        <option value="PARCEIRO">PARCEIRO</option>
                        <option value="OUTRO">OUTRO</option>
                    </select>
                </div>  
              </div>               
            </div>
            <div class="row">
              <div class="form-group">
                <div class="col-md-12">
                    <label for="ob">Observações:</label>                 
                    <textarea rows="5" class="form-control" id="ob" name="ob" placeholder="Se caso haver alguma observação digite aqui"></textarea>
                </div>
              </div>
            </div>
            <div class="text-right col-md-12">
                <button id="submit" type="submit" class="btn btn-primary">Enviar</button>
            </div>
        </form> 
    </body>
</html>

  • It didn’t work, you can explain to me why you put that part: . Closest('. form-group')

  • This method is the one that seeks which tag must have the class changed after validation, but as I noticed that I was using bootstrap and this class is always used in creating Forms, I passed that I did not have them in your code, I edited the part of html, if it does not work, return with the error or some relevant information so that we can get right...

  • Unfortunately it didn’t work again friend, I’ve checked everything the class has-error is like this in css: . has-error, #&Xa; color: #ed3237! Mportant; }, and yet it’s not working, you want me to send you my code to see this error?

  • You are running in which browser? give a F12 and see if there is any error in javascript. Even if the rule is created in css, you need to make sure that the class is being added to the element...

  • Yes I checked and this with no error in the execution.

  • It seems that the script is not running because before it was putting the red input edges and now it is no longer running.

  • The class has-error is being inserted? If not, put a alert('entrou') before the line you should insert to see if you are entering this section...

  • Thus Alert: Highlight: Function(element) { Alert('entered'); }, unhighlight: Function(element) { Alert('entered'); },

  • Just remembering friend I want to change the Label color of the input that was not filled, as in the image I showed.

  • Yes, that’s what you should do, because this class is already bootstrap standard, if you are entering the event, then you need to fix it is the selector, I will change the answer with another...

  • I tried this way and it didn’t work look: $("#my-form"). validate({ Highlight: Function(element) { $(element). Closest('. labell'). addClass('has-error'); }, unhighlight: Function(element) { $(element). Closest('. labell'). removeClass('has-error'); },

  • It is not the most "beautiful", but it can work, try this please!

  • Nothing, some kind of feedback?

Show 8 more comments

3

One simple way to do this is to assign the classes through the object parameters, using errorClass or validClass, and set the color of these classes in the CSS:

jQuery:

$("#my-form").validate({
   errorClass: "my-error-class",
   validClass: "my-valid-class"
});

CSS:

.my-error-class {
    color:#FF0000;  /* red */
}
.my-valid-class {
    color:#00CC00; /* green */
}

Example in JSFIDDLE

Source of the problem in Soen

To get the label:

$("#my-form").validate({
    errorClass: "my-error-class",
    validClass: "my-valid-class",
    highlight: function (element, errorClass, validClass) {
          //element.id é a ID do input
        $(element.form).find('label[for="lb_'+element.id+'"]')
        .addClass(errorClass);
    },
    unhighlight: function (element, errorClass, validClass) {
        $(element.form).find('label[for="lb_'+element.id+'"]')
        .removeClass(errorClass);
    },
    rules: {
            test: {
                required: true,
                minlength: 12
            }
    }
});

Example in JSFIDDLE

  • I’ll try here buddy, just a minute!

  • I have to change the Input Label that was not filled in understood friend?

  • As in the example I sent the photo, please help me.

  • I edited the question, in case you change the label, remembering that you can pass the id no for: .find('label[for="'+element.id+'"]')

1


Usually I do this using the same classes that jQuery Validate implements in the error elements.

$("#form-validate").validate({
    rules: {
      nome: "required",
      telefone: "required"
    }
});
label.error{
  display: none!important;
}

.error{
  background-color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.8/jquery.validate.js"></script>
<form id="form-validate"> 
    <labe>Nome</label>
    <input type="text" name="nome" /> 
  
  <label>Telefone</label>
    <input type="text" name="telefone" /> 
  
   <input type="submit" value="Enviar">
</form>

Running on the Codepen

  • I don’t know why, but it doesn’t work on Sopt’s Sandbox. But on Codepen it’s fine.

Browser other questions tagged

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