Page updated Mar 26, 2024

Validate form data

Sanitize user input by adding validation rules to your form. By default, Amplify Studio infers a range of validation rules based on the data model. For example, given a data model with an AWSEmail field, the generated form input will automatically run an email validation rule.

Add validation rules

In Amplify Studio, you can visually add validation rules to inputs. If a form input has multiple validation rules, then all rules must be met for the input to be valid.

  1. Select a form input
  2. Go to Validation rules > Add rule
  3. Select a validation type
  4. Enter values for the validation
  5. Optional: Customize the error message presented to the end user. Note: Studio automatically generates an error message based on the validation type and its values.
  6. Click out of the validation rule popover

To test the validation rules, select View as end user.

Available validation rules within Amplify Studio

By default, the following validation rules are available for you to configure:

Input typeConfigurable validation rule
String- Start With
- End With
- Contain
- Does not contain
- Be less than N characters long
- Be at least N characters long
Int, Float- Be greater than
- Be less than
- Be equal to
AWSDate, AWSTime, AWSDateTime- Be before
- Be after

Automatically configured validation rules

For the types below, Amplify Studio automatically applies validation rules on form inputs:

  • AWSIPAddress: input value must be a valid IPv4 or IPv6 address.
  • AWSURL: input value must consist of a schema (http, mailto) and a path part. Path part can't contain two forward slashes (//).
  • AWSEmail: input value must be an email address in the format <local-part>@<domain-part>.
  • AWSJSON: input value must be a valid JSON.
  • AWSPhone: input value must be a phone number that can contain either spaces or hyphens to separate digit groups.

Extend validation rules with code

Every form provides an onValidate event handler to provide additional validation rules via code. These validation rules are run after the rules you configured in the Studio console.

Return an object with validation functions for the fields you want to validate. In the example below, address must start with a number, otherwise return any existing auto-generated validation responses.

1<HomeCreateForm
2 onValidate={{
3 address: (value, validationResponse) => {
4 const firstWord = value.split('')[0];
5 if (!isNaN(str)) {
6 // check if the first word is a number
7 return {
8 hasError: true,
9 errorMessage: 'Address must start with a number'
10 };
11 }
12 return validationResponse;
13 }
14 }}
15/>

Note: the validation function must return a validation response of the following shape:

1type ValidationResponse = {
2 hasError: boolean;
3 errorMessage?: string;
4};

Add validation rules for nested JSON data

Amplify Studio Forms can also produce nested JSON object. For example, you can create a new ProductForm component based on the following JSON object:

1{
2 "name": "Piano",
3 "price": {
4 "maxDiscount": 0.15,
5 "default": 999,
6 "currency": "$"
7 }
8}

To add validation rules to the nested objects, pass in validation functions in the same nested structure as the data:

1<ProductForm
2 onValidate={{
3 price: {
4 currency: (value, validationResponse) => {
5 // Pass validation function to match the nested object
6 const allowedCurrencies = ['$', '€', '¥', '₹'];
7 if (!allowedCurrencies.includes(value)) {
8 return {
9 hasError: true,
10 errorMessage: 'Currency must be either "$", "€", "¥", or "₹".'
11 };
12 }
13 return validationResponse;
14 }
15 }
16 }}
17 onSubmit={(fields) => {
18 /* handle form data submission */
19 }}
20/>

Call external APIs for asynchronous form validation

Sometimes your form needs to asynchronously validate an input with an external API or database before the form data is submitted.

Return a Promise in the onValidate prop to run an asynchronous validation rule. In the following example, we check with an external API if a real estate agent exist based on a given license number:

1<AgentContactForm
2 onValidate={{
3 licenseNumber: (value, validationResponse) => {
4 // fetch calls an external API,
5 // which ultimately returns a Promise<ValidationResponse>
6 return fetch(`http://localhost:3000/api/agent/${value}`).then(
7 (response) => {
8 if (response.status !== 200) {
9 return {
10 // If the request failed, return a validation error
11 hasError: true,
12 errorMessage: 'No agent was not found with that license number.'
13 };
14 }
15 return validationResponse;
16 }
17 );
18 }
19 }}
20 onSubmit={(fields) => {
21 /* Handle form submission */
22 }}
23/>