To add validation to a custom input field, you can use JavaScript to check the value of the input field and display an error message if the value is not valid.
Here’s an example of a custom input field that validates the email address entered by the user:
class EmailInput extends HTMLElement {
constructor() {
super();
this.innerHTML = `
<label>Email</label>
<input type="email" required>
<div class="error"></div>
`;
this.querySelector('input').addEventListener('input', this.validate.bind(this));
}
validate() {
const input = this.querySelector('input');
const error = this.querySelector('.error');
if (input.validity.valid) {
error.textContent = '';
} else {
error.textContent = 'Please enter a valid email address';
}
}
}
customElements.define('email-input', EmailInput);
In this example, the custom input field listens for the input event on the input element, and when the event is fired, it calls the validate() method. Inside the validate() method, it checks the validity property of the input element and if it is not valid it will set the error message in the error div.
You can also use other validation techniques like regular expressions, and you can also add more validation checks to match your requirements. You can also add styles to the error message to make it stand out more.
It’s worth noting that, you can also validate input fields on form submit event, by adding a submit event listener on the form element, and check the validity of the input fields in the submit event listener.
const form = document.querySelector('form');
form.addEventListener('submit', (event) => {
event.preventDefault();
const emailInput = form.querySelector('email-input');
if(!emailInput.validate()) {
return;
}
//submit the form
});
This way you can ensure that the form is only submitted when all the input fields are valid.