Hello,
Is there a way to have multiple validators on a field, like a require validator that check if the field is not empty and another that check if the field is a URL for example.
I tried to setup the validator parameter like this without success:
:validator="[requiredValidator, urlValidator]"
Regards,
Fabien
Hello, Fabien.
Yes, we can use multiple validators per field that is part of the Native Form component.
Here is a StackBlitz example demonstrating how the discussed functionality can be implemented. In it we have the following validation functions:
const emailValidator = (value) => emailRegex.test(value) ? "" : "Please enter a valid email."; const lengthValidator = (value) => value && value.length > 10 ? "" : "Please enter email with more than 10 characters.";
Each of the above functions is passed to the Form field using the following configuration:
<field :name="'email'" :type="'email'" :component="'myTemplate'" :label="'Email'" :validator="[emailValidator, lengthValidator]" > ................
I hope the above example will help you implement what you need in your project.
For example: I may want to validate an email input, but the field is optional, I will have this validator :
return emailRegex.test(value) || value === '' ? '' : 'LNG_BAD_FORMAT';
return value ? '' : 'LNG_FIELD_REQUIRED';
<field :name="'email'" :type="'email'" :component="'myTemplate'" :label="'Email'" :validator="[emailValidator, requiredValidator]" >
This means I will have to write specific validator for each use case then (requiredEmailValidator, optionalEmailValidator, etc). :/
Hi, SysCo.
The way validators work is that they require all methods passed to the validator prop to return true. This can be observed in the example I sent you. You can enter "@abc.com" and the result will be:
Then, if you add a letter before the "@" sign, the result will be:
Talking specifically about the scenario with the required and requiredOptional fields, yes, with the current implementation of the Form, you will need to define separate functions that handle the two scenarios.