Input alert if typed data is invalid

Asked

Viewed 475 times

0

Suppose there is an input that receives a phone number. If the mask returns that it is 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 much notion of JS interaction, just managed to give the message through the alert, but let’s face it, it’s kind of boring.

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

  • 1

    There are several ways to do it, depending on what is "alert" for you.

  • Anything around the input. Whether to change the edge of it, insert a div next to the form, things like that, right into html

2 answers

5

Can use :invalid to validate a field (text, number, email, etc...) and through this rule, decide whether to display/hide the alert to 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>

1

Another way is by using the attribute Pattern of HTML.

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, Pattern is for telephone, in format 99-99999-9999.

Jsfiddle: https://jsfiddle.net/lbclucascosta/d414erhL/

Browser other questions tagged

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