Input alert if given entered is invalid

0

Suppose there is an input that receives a phone number. If the mask returns it to be invalid, how to insert a warning (html and css) in the input to tell the user that the data is invalid? I do not have a lot of interaction with JS, I just got the message through alert , but let's face it, it's kind of annoying.

NOTE: I want a solution without the use of jQuery.

    
asked by anonymous 14.12.2016 / 15:41

2 answers

5

You can use :invalid to validate a field (text, number, email, etc ...) and by means of this rule, decide whether to show / hide the alert for the user:

.input span {
  color: red;
  display: none /* Esconde o span */
}

.input input:invalid + span {
  display: inline /* Exibe o span somente se o input for inválido. */
}
<div class='input'>
  <input type='email' placeholder='[email protected]'>
  <span>email inválido.</span>
</div>
    
14.12.2016 / 16:00
1

Another way is to use the HTML pattern attribute.

HTML:

<form>
  <label for="choose">Qual seu telefone?</label>
  <input id="choose" name="i_like" pattern="[0-9]{2}-[0-9]{5}-[0-9]{4}" required>
  <button>Enviar</button>
</form>

CSS:

input:invalid {
  border: 1px solid red;
}

input:valid {
  border: 1px solid green;
}

In this example, the pattern is for phone, in 99-99999-9999 format.

JSFiddle: link

    
14.12.2016 / 17:03