required: Specifies that a field must be filled in.minlength and maxlength: Define the minimum and maximum length for text inputs.min, max, and step: Specify the allowed range and increment for numerical inputs.type: Specifies the data type, such as email, number, or URL.pattern: Uses regular expressions to define a custom validation pattern.HTML Code:
<form>
<label for="choose">Would you prefer a banana or a cherry? (required)</label>
<input id="choose" name="i-like" required />
<button>Submit</button>
</form>
CSS Code:
input:invalid {
border: 2px dashed red;
}
input:invalid:required {
background-image: linear-gradient(to right, pink, lightgreen);
}
input:valid {
border: 2px solid black;
}
Explanation:
This example demonstrates the use of the required attribute to make the input field mandatory. The CSS styles provide visual feedback based on the validity of the input.
validationMessage, validity, willValidate.checkValidity(), reportValidity(), setCustomValidity().HTML Code:
<form>
<label for="mail"> I would like you to provide me with an email address: </label>
<input type="email" id="mail" name="mail" />
<button>Submit</button>
</form>
JavaScript Code:
const email = document.getElementById("mail");
email.addEventListener("input", (event) => {
if (email.validity.typeMismatch) {
email.setCustomValidity("I am expecting an email address!");
} else {
email.setCustomValidity("");
}
});
Explanation:
This example uses the setCustomValidity() method to display a custom error message if the entered value is not a valid email address.