Logotype Sitevision Developer
Log in
Log in

Default validation

By default, elements with the required attribute are validated.

js
// 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.

js
// 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(); };

Error messages

Custom validation functions might need to display error messages. The sv.addErrorMessages function will add them in a standardized fashion and allows easy revalidation on change.

js
// 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 */
html
<!-- 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.

js
(() => { 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(); }; })();
Did you find the content on this page useful?