Velo: About Validating User Input with Code
Whenever possible, your form validation should prevent users from entering invalid values. In cases where you can't prevent the invalid data from being entered, you should check the data before submitting it and notify the user if it's invalid.
Velo allows you to set up some field-level validation using the settings of the User Input elements. Additional validation can be added using JavaScript code.
This article focuses on the the code-based validations. To learn more about field-level validations using the settings of the User Input elements, see Validating User Input with Settings.
Note that custom validationsare not run on Input elements when they don't have a value.
Typical Validation Scenario
Typically, to add custom validation you add custom validation logic in an event handler that you set using the Input element's onCustomValidation()
function. Within that handler, you call the reject()
function to indicate that the element is invalid. The element's validity is checked when the value of the element changes either by user interaction or programmatically.
Example
To do so we add the following code in the page's onReady()
function:
1$w.onReady(function () {
2 $w("#textInput1").onCustomValidation( (value, reject) => {
3 if( !value.endsWith("@wix.com") ) {
4 reject("Email address must be a wix.com address.");
5 }
6 });
7});
On line 2 we call the element's onCustomValidation()
function to register the event handler that is called when the element is being validated. That function receives two parameters, value
and reject
. The value
parameter is the current value of the element that is being validated. The reject
parameter is a function that we can call to invalidate the element.
On line 3 we check to see if the value
doesn't end with wix.com
.
On line 4, which is reached only if the value
doesn't end with wix.com
, we invalidate the element using the reject()
function and pass it a rejection message.
Additional Validation Functionality
valid
The valid
property indicates if an element's value is valid. It takes both standard and custom validation into consideration.
validity
The validity
property returns a ValidityState
object that contains detailed information about why an element is invalid.
validationMessage
The validationMessage
property returns a message indicating why an invalid element is invalid. You can set the validationMessage
using the reject()
function. If you don't set a custom message, the validationMessage
may contain a standard validation message, such as "value missing"
or "type mismatch"
.
resetValidityIndication()
The resetValidityIndication()
function clears the visual cue that signifies that an element is invalid.
updateValidityIndication()
The updateValidityIndication()
function updates the visual cue that signifies whether an element is invalid based on the element's current validity state.