Stylize Required

1

Instead of appearing in that text box, I would like only the edges of my input to be red when the user does not fill them. is there any way to do this?

    
asked by anonymous 04.08.2018 / 14:57

2 answers

2

Using JavaScript you can do without using required .

Add a .required class to the fields you want to be filled in and use the script that will check those fields in the submit, changing the border color of those that have not been filled:

formulario.onsubmit = function(){
   var req = document.querySelectorAll(".required");
   var flag = true;
   for(var x=0; x<req.length; x++){
      if(!req[x].value){
         req[x].style.borderColor = "red";
         flag = false;
      }
   }
   
   return flag;
}
<form id="formulario">
   <p>
      <input type="text" placeholder="Preenchimento opcional">
   </p>
   <p>
      <input type="text" class="required" placeholder="Preenchimento obrigatório">
   </p>
   <button>Enviar</button>
</form>
    
04.08.2018 / 16:08
2

You can treat this with pseudo-classes :invalid , :focus , and :valid

Note that the order must be the order for the styles to not overwrite incorrectly. First it becomes invalid and red until you focus on the field, there it turns blue, and in case you fill in something it turns green.

See the example below for a better understanding.

input:invalid {
    border: 2px solid red;
}
input:focus {
    border: 2px solid blue;
}
input:valid {
    border: 2px solid green;
}
<input type="text" required>

EDIT: Formatting example without required

Since this field has not been valid or invalid, it only changes color in: focus and when you click it it turns green because it is always valid since it does not have rules like patterns or maxlength for example. ..

input:focus {
    border: 2px solid blue !important;
}
input:valid {
    border: 2px solid green;
}
<input type="text">

OBS: This is a user-side only validation to give visual feedback to the user, these css styles are not valid for the fields in the database, they are only worth improving the user experience in the interface.

    
04.08.2018 / 15:51