Dropdown interaction with Validation functions
In this section, you will see how you can combine Dropdown functionality with Validation functions if you so desire that a field is actually constrained to those set of valid options.
By default, dropdowns act as guides for the user rather than being hard restrictions on the values that can be entered in a field. Even if a field is constrained to a set of possible values, it’s still possible for the autocomplete engine to synthesize values that don’t match.
If it is desired that the field is actually constrained to those set of valid options, this can be achieved using a custom validation function along with the `validOptions`. This isn’t enabled by default since there are a wide variety of complicated business rules that can be represented using the dynamically retrieved valid options and it could possibly conflict with those in unexpected ways.
Custom validators have this function signature:
1
type ValidationResult = boolean | { errorMessage?: string } | string;
2
3
type ValidationFunction = (rows: (string | null)[][]) =>
4
Promise<ValidationResult[]>;
Copied!
The custom validation function passed to `validator` receives the current values of all output rows as a 2D array, allowing all rows to be validated at once for efficiency. The return value is an array of validation results for each row which must be the same length as the provided `rows` array.
Here’s an example of a validation function that actually does constrain the values entered (or synthesized) for the “Payment Type” field to match one of the valid options:
1
{
2
name: 'paymentType',
3
validOptions: ['cash', 'credit', 'debit', 'paypal'],
4
validator: async (rows) => {
5
return rows.map((row) => {
6
const paymentType = row[0];
7
if (!['cash', 'credit', 'debit', 'paypal'].includes(paymentType)) {
8
return 'This field must be one of the valid payment types';
9
}
10
11
return true;
12
});
13
}
14
}
Copied!
If invalid values are synthesized, they will be marked as errors with the custom error message in the UI shown to the user:
Customizable error message in the UI
Last modified 4mo ago
Copy link