Example – validating form inputs with custom events
The example that we are going to explore is using actions to validate form inputs.
When you add an input element to your form, you can add attributes such as required
, minlength
, and min
to indicate that the input value has to pass the constraint validation or else would be considered invalid.
However, by default, such a validation check is only done during form submission. There’s no real-time feedback on whether your input is valid as you type.
To make the input element validate as you type, we need to add an 'input'
event listener (which will be called on every keystroke as we type in the input element) and call input.checkValidity()
to validate the input. Now, let’s do just that:
<input on:input={(event) => event.target.checkValidity()} />
As you call the checkValidity()
method, if the input is indeed invalid, then it will trigger the '
invalid'
event:
<input...