Warning
You're browsing the documentation for an old version of Webiny. Consider upgrading your project to Webiny 5.41.x.
WHAT YOU'LL LEARN
  • what is a field validator
  • how to add a validator to a content model’s field
  • how to test the applied validator

A field validator helps you ensure the user input meets specific requirements and matches the expected format for a field.

In this tutorial, we will learn how to add validators to a content model’s fields. As an example, we will add validators to the LONG TEXT and NUMBER fields used in the Product content model that we created in the Create Content Model tutorial.

Step 1: AddRequiredandMin lengthValidators to a LONG TEXT Field
anchor

In this step we will:

  • make the Description field required.
  • set the minimum length for the input the Description field to 20 characters.
  1. From the Side Menu, Click Headless CMS > Models.

    ✔️ The Content Models screen opens.

  2. Hover on the Product content model.

  3. Click the EDIT CONTENT MODEL icon (✏️).

    ✔️ Screen to configure the Product content model’s fields opens.

  4. Click the EDIT FIELD icon (✏️) on the Description field.

    ✔️ Field Settings - Long Text screen opens.

  5. Click the VALIDATORS tab.

  6. Enable the Required validation by toggling the Enabled button. This will make the Description field mandatory.

    ✔️ Message textbox will be shown to set the error message.

  7. In the Message textbox, type Please enter the product description.

  8. Enable the Min length validation by toggling the Enabled button.

    ✔️ Message and Value textboxes will be shown to set the error message and minimum value.

  9. In the Message textbox, type Description cannot be less than 20 characters.

  10. In the Value textbox, type 20.

  11. Click SAVE FIELD.

✔️ Screen to configure the Product content model’s fields opens.

  1. Click SAVE.

    ✔️ “Your content model was successfully saved!” will be displayed.

Step 2: Test the Validators
anchor

  1. Click the PREVIEW tab in the Product Model screen.

  2. Click the Description textbox.

  3. Now click anywhere outside the Description textbox.

    ✔️ The message “Please enter the product description” appears.

  4. In the Description textbox, type Top sweatshirt.

  5. Now click anywhere outside the Description textbox.

    ✔️ The message “Description cannot be less than 20 characters” appears.