Some apps have inputs in their control panel that must be validated, these inputs may display an error message in case the user makes a mistake. It is very important to provide a friendly user experience to avoid frustrations, for that reason we are going to show you through an example how we create field validations for our apps.

See the example below:

From Instagram’s control panel

From Instagram’s control panel

Importing the components

You don’t need to create new components for your input field or your label, instead, you can import them from smart-builder-components like this:

import { InputField, Label } from 'smart-builder-components';

For the error message, we don't have a component in smart-build-components yet. Usually we create one like this:

import styled from 'styled-components';
import { colors, spacing, fontSize } from 'smart-builder-sdk';

export const Error = styled.span`
  margin-top: ${spacing.lg};
  color: ${colors.red};
  font-size: ${fontSize.textSm};
`;

You can import color, spacing and fontSize from the smart-builder-sdk .

Example

In the control panel, add your inputs and validations, here is a simple example of how you can do this:

import React, { useState } from 'react';
// Our Input Fiel and Label components
import { InputField, Label } from 'smart-builder-components';
// Here we import the Error component we have created
import { StyledFormControl, Error } from './styled';

import { ExampleAppData } from 'src/types';
import { ControlPanelProps } from 'unbounce-smart-builder-sdk-types';

import { checkUrl } from '../../util/check-url';

export const Panel = ({ data, dispatch }: ControlPanelProps<ExampleAppData>) => {
  const { src } = data;
  const [tempSrc, setTempSrc] = useState(src);

  const onUrlChange = () => {
    dispatch((api) => {
      api.get('src').set(tempSrc);
    });
  };

  // Check URL
  const urlError = tempSrc && checkUrl(tempSrc);

  // Our Panel control
  return (
    <>
      <StyledFormControl>
        <Label>Write your URL</Label>
        <InputField
          type="text"
          id="url-input"
          value={tempSrc}
          onChange={({ currentTarget: { value } }) => setTempSrc(value)}
          onBlur={onUrlChange}
          placeholder="Enter URL..."
          minimal
        />
      </StyledFormControl>

      {urlError && <Error>Oops! That URL doesn&apos;t look right. Please check it is correct and try again.</Error>}
    </>
  );
};