Validación de formularios JavaScript


Tabla de contenido

    Mostrar tabla de contenidos


Métodos DOM de validación de restricciones

checkValidity()

Devuelve verdadero si un elemento de entrada contiene datos válidos.

setCustomValidity()

Establece la propiedad validationMessage de un elemento de entrada.


Si un campo de entrada contiene datos no válidos, muestra un mensaje:

El método checkValidity()

<input id="id1" type="number" min="100" max="300" 
    required>
<button onclick="myFunction()">OK</button>
<p id="demo"></p>
<script>
 function myFunction() {
  const inpObj = document.getElementById("id1");
  if (!inpObj.checkValidity()) {
    document.getElementById("demo").innerHTML = inpObj.validationMessage;
    }
}
</script>

Pruébelo usted mismo →

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Validation</h2>

<p>Enter a number and click OK:</p>

<input id="id1" type="number" min="100" max="300" required>
<button onclick="myFunction()">OK</button>

<p>If the number is less than 100 or greater than 300, an error message will be displayed.</p>

<p id="demo"></p>

<script>
function myFunction() {
  const inpObj = document.getElementById("id1");
  if (!inpObj.checkValidity()) {
    document.getElementById("demo").innerHTML = inpObj.validationMessage;
  } else {
    document.getElementById("demo").innerHTML = "Input OK";
  } 
} 
</script>

</body>
</html>

Propiedades DOM de validación de restricciones

validity

Contiene propiedades booleanas relacionadas con la validez de un elemento de entrada.

validationMessage

Contiene el mensaje que mostrará un navegador cuando la validez sea falsa.

willValidate

Indica si un elemento de entrada será validado.



Propiedades de validez

La propiedad de validez de un elemento de entrada contiene un número de propiedades relacionadas con la validez de los datos:

customError

Establecer en verdadero, si se establece un mensaje de validez personalizado.

patternMismatch

Se establece en verdadero si el valor de un elemento no coincide con su atributo de patrón.

rangeOverflow

Se establece en verdadero si el valor de un elemento es mayor que su atributo máximo.

rangeUnderflow

Se establece en verdadero si el valor de un elemento es menor que su atributo mínimo.

stepMismatch

Se establece en verdadero si el valor de un elemento no es válido según su atributo de paso.

tooLong

Se establece en verdadero si el valor de un elemento excede su atributo maxLength.

typeMismatch

Se establece en verdadero si el valor de un elemento no es válido según su atributo de tipo.

valueMissing

Se establece en verdadero si un elemento (con un atributo obligatorio) no tiene valor.

valid

Se establece en verdadero, si el valor de un elemento es válido.


Ejemplos

Si el número en un campo de entrada es mayor que 100 (el max de la entrada atributo), muestra un mensaje:

La propiedad rangeOverflow

<input id="id1" type="number" max="100">
<button onclick="myFunction()">OK</button>

<p id="demo"></p>

<script>
function myFunction() {
  let text = "Value OK";
    if (document.getElementById("id1").validity.rangeOverflow) {
      text = "Value too large";
    }
}
</script>

Pruébelo usted mismo →

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Validation</h2>

<p>Enter a number and click OK:</p>

<input id="id1" type="number" max="100">
<button onclick="myFunction()">OK</button>

<p>If the number is greater than 100 (the input's max attribute), an error message will be displayed.</p>

<p id="demo"></p>

<script>
function myFunction() {
  let text;
  if (document.getElementById("id1").validity.rangeOverflow) {
    text = "Value too large";
  } else {
    text = "Input OK";
  } 
  document.getElementById("demo").innerHTML = text;
}
</script>

</body>
</html>

Si el número en un campo de entrada es menor que 100 (el atributo min de la entrada), muestre un mensaje:

La propiedad rangeUnderflow

<input id="id1" type="number" min="100">
<button onclick="myFunction()">OK</button>

<p id="demo"></p>
<script>
function myFunction() {
  let text = "Value OK";
    if (document.getElementById("id1").validity.rangeUnderflow) {
      text = "Value too small";
    }
}
</script>
 

Pruébelo usted mismo →

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Validation</h2>

<p>Enter a number and click OK:</p>

<input id="id1" type="number" min="100">
<button onclick="myFunction()">OK</button>

<p>If the number is less than 100 (the input's min attribute), an error message will be displayed.</p>

<p id="demo"></p>

<script>
function myFunction() {
  let text;
  if (document.getElementById("id1").validity.rangeUnderflow) {
    text = "Value too small";
  } else {
    text = "Input OK";
  } 
  document.getElementById("demo").innerHTML = text;
}
</script>

</body>
</html>