Validation
Validation can be defined for each fields using the required
and validation
keys.
The required
key only specify if the field is required and not null in the values inserted by the form user, while the
validation
key defines some rules about the inserted value:
The validation object
Key | Type | Description |
---|---|---|
minLength | number | Minimum length, for string fields |
maxLength | number | Maximum length, for string fields |
min | number | Minimum value, for numeric fields |
max | number | Minimum value, for numeric fields |
message | string / i18n | The message to display if validation fails |
pattern | string | A regular expression used to validate a string value, omit the / s (i.e., use [a-z0-9] and not /[a-z0-9]/ |
validate | string | JavaScript code for validation |
For example
{
"version": "1",
"fields": [
{
"name": "my_field",
"label": "My field",
"component": "input-text",
"required" true,
"validation": {
"minLength": 5,
"maxLength": 10,
"message": "There's something wrong with this value"
}
}
]
}
I18N support
I18N is supported in the validation message
key
{
"version": "1",
"fields": [
{
"name": "my_field",
"label": "My field",
"component": "input-text",
"required" true,
"validation": {
"minLength": 5,
"maxLength": 10,
"message": {
"en-US": "There's something wrong with this value",
"it-IT": "C'e' qualcosa che non va in questo valore"
}
}
}
]
}
Custom JavasScript validator
More complex validation can be implemented with some simple JavaScript using the validate
keys
{
"version": "1",
"fields": [
{
"name": "my_field",
"label": "My field",
"component": "input-text",
"required" true,
"validation": {
"message": "There's something wrong with this value",
"validate": "if (value.length < 10) { return false; }"
}
}
]
}
In this simple example it just checks for the string to be at least 10 chars.
In the JavaScript code, these variables are available:
value
is the value inserted by the user for the specific fieldformValues
is a hash with all current values of the form
The JavaScript code should return
true
ornull
orundefined
or nothing if the value is to be considered invalidfalse
if the value is invalid, in that case will be shown the error message defined inmessage
or the default one- string or a i18n object if the value is not valid and a customi error should be shown
For example, in order to return a custom localized error message
{
"version": "1",
"fields": [
{
"name": "my_field",
"label": "My field",
"component": "input-text",
"required" true,
"validation": {
"message": "There's something wrong with this value",
"validate": `if (value.length < 10) {
return {
'en-US': 'There\'s something wrong with this value',
'it-IT': 'C\'e\' qualcosa che non va in questo valore'
};
}`
}
}
]
}