WebApps 2
Validation
Default validation
By default, elements with the required
attribute are validated.
// Default validate function
window.validate = function () {
return window.sv.validate();
};
Custom validation
To add custom validation, overwrite the default validation function.
To keep default validation and add additional validation, the internal function sv.validate
should be called from the overwritten version.
The example below will add validation for email inputs and keep default validation for required fields.
// Overwrite default validate function
window.validate = () => {
const emailInputs = document.querySelectorAll('input[type=email]');
let valid = true;
emailInputs.forEach((emailInput) => {
if (!emailInput.validity.valid) {
valid = false;
}
});
// Add call to sv.validate() for both custom
// and default validation.
return valid && window.sv.validate();
};
// Add Error Message Method
window.sv.addErrorMessage(element, options);
/*
Parameters:
element: HTMLElement
options: {
component: HTMLElement,
message: String,
position: String,
isValid: Function
}
position:
Possible values: 'beforebegin', 'afterbegin', 'beforeend', 'afterend'.
Default value: 'beforeend'
isValid:
The input onChange event will use this method to check if new value is valid.
Return true to remove error message.
*/
// Remove Error Message Method
window.sv.removeErrorMessage(HTMLElement);
/*
Parameters:
element: HTMLElement
*/
<!--
Data Attributes:
data-sv-validation-component:
May be used on the container element instead of passing
the component parameter to validation.addErrorMessage.
data-sv-validation-error-msg:
May be used on the input element instead of passing
the message parameter to validation.addErrorMessage.
-->
<div class="custom-component"
data-sv-validation-component>
<div class="custom-component-element">
<input class="custom-component-input"
data-sv-validation-error-msg="Custom error message">
</div>
</div>
Example
This example will add email validation and display custom error messages.
(() => {
window.validate = () => {
const emailInputs =
document.querySelectorAll('input[type=email]');
let valid = true;
emailInputs.forEach((emailInput) => {
if (!emailInput.validity.valid) {
valid = false;
window.sv.addErrorMessage(emailInput, {
message: emailInput.validationMessage,
isValid: function (e) {
return e.target.validity.valid;
},
});
}
});
return valid && window.sv.validate();
};
})();