Validation

Scripts allow you to validate field values and avoid errors when filling out forms.

Make sure the end date doesn’t come before the start date

For example, suppose we want to automatically check if the dates are correctly filled out in a business trip form. We created this form earlier in the Getting started article. Let’s configure the automatic date check by adding the following code to the form’s script:

form.onChange(['Start Date', 'End Date'])
  .validate('End Date', state => {
    const [start, end] = state.changes;

    if (!start || !end)
      return null;

    if (start.date && end.date && start.date >= end.date)
      return {
        errorMessage: 'Can’t be earlier than start date'
      };

    return null;
  });

Now, if we accidentally designate an end date that’s earlier than the start date, the form will return an error message.

Make sure at least one field is filled out

This script checks if one or several form fields are filled out. Suppose you need to check if a client filled out an email or a phone number in a service ticket form. Use the following script:

form.onChange(['Email', 'Phone'])
  .validate('Phone', state => {
    const [email, phone] = state.changes;

    const emailIsEmpty = !email || !email.text;
    const phoneIsEmpty = !phone || !phone.text;

    if (emailIsEmpty && phoneIsEmpty)
      return {
        errorMessage: 'Add your email or phone number.'
      };

      return null;
  });

We added the list of fields to the onChange method. Then we added a check to ensure at least one of the fields is filled out. If not, the user will get the error message stored in the errorMessage key.

Was this article helpful?