Event handler
A Validation
object can be used as an event handler. When executed on the client side, it is just a wrapper over the Validation().validate()
method and can be passed directly into the addEventListener()
method.
Syntax
Validation()()Validation()(event)element.addEventListener(type, Validation())
Parameters
event
optional
AnEvent
object. (Only the propertytarget
is used to validate predicate groups associated with the object it refers to.)
Default:undefined
.
Return value
See “Return value” of the Validation().validate()
method.
Exceptions
See “Exceptions” of the Validation().validate()
method.
Description
Using a Validation
object as an event handler is intended to reduce boilerplate.
Examples
Validation
as an event handler
Consider the code below. The grouping Validation
object was added as an event handler
form.addEventListener('input', validation);
instead of creating an event handler function
form.addEventListener('input', (event) => validation.validate(event.target));
import { Validation } from "isomorphic-validation";
// predicate functionsconst isLessThan45 = (value) => Number(value) < 45;const isGreaterThan21 = (value) => Number(value) > 21;const isLessThan300k = (value) => Number(value) < 300000;const isGreaterThan20k = (value) => Number(value) > 20000;
// <form name="form">// <input type="number" name="age" placeholder="Age"/>// <input type="number" name="salary" placeholder="Salary"/>// <input type="submit" name="submitBtn" disabled />// </form>const { form } = document;const { age, salary, submitBtn } = form;
const validation = Validation.group(
Validation(age) .constraint(isGreaterThan21) .constraint(isLessThan45),
Validation(salary) .constraint(isGreaterThan20k) .constraint(isLessThan300k),
).changed( // enable and disable the submit button ({isValid}) => submitBtn.disabled = !isValid);
form.addEventListener('input', validation);
// the line above is equivalent to this:// form.addEventListener('input', (event) => validation.validate(event.target));
Depending on your code style, you could even define the whole Validation
without assigning it to a variable and instead pass it right immediately into the addEventListener()
method:
form.addEventListener( 'input', Validation.group(
Validation(age) .constraint(isGreaterThan21) .constraint(isLessThan45),
Validation(salary) .constraint(isGreaterThan20k) .constraint(isLessThan300k),
).changed( // enable and disable the submit button ({isValid}) => submitBtn.disabled = !isValid ));