Open In App

React Suite Components Form validation

Improve
Improve
Like Article
Like
Save
Share
Report

React Suite is a front-end library, containing a wide range of React Components used in enterprise applications. This article discusses how the React suite’s Form Validation helps developers add validation to forms. Form Validation involves providing prompt information to the user when there is an error in the data entered with the form. Form validation is useful to ensure that the form data entered is logical and submitted in the prescribed order.

In rsuite, for verifying the form data, we can use the following approaches:

  • Schema from rsuite
  • SchemaModel from schema-typed library

Default check in rsuite: The form will automatically trigger the data check activity after the submit event is triggered i.e when the user clicks on submit. It involves passing the form data entered as props to a function that would check the entered data in the TextField after the submit event is triggered.

 

Schema Model: The syntax for creating the data model using Schema Model

import { Schema } from "rsuite"
const model = Schema.Model({
    // Here we declare the following properties
    name: Schema.Types.StringType()
        .isRequired('This field is required.'),
    email: Schema.Types.StringType()
        .isEmail('Please enter a valid email address.')
});

In the above schema model, we declare a model with the schema: name and email.

Rules for field Level verification: Field-level verification involved providing individual value validation functions for each Field or FieldArray.

Following are the rules for adding field-level verification in rsuite:

  • Use the <Form.control> to add field-level verification.
  • Use the rule attribute.
  • The rule name should be defined as a variable using Schema.Types.StringType() following the rule.

Asynchronous check: The asynchronous check involves verifying data as it is being entered into the form. Conditions under which, we need to perform asynchronous verification on the data include, verifying whether the username is duplicated or the email already exists. This helps users quickly identify if the entered data is unique or not. 

Custom Form.Control: The Form.Control component is used for data management and data associated with the Form component. 

  • Used to bind data fields in a Form, passing the name attribute to the key of the Schema.Model object.
  • The default is an Input component, which can be set through the Ê»accepter` component.

Third-Party Libraries: Third-party libraries can be used when we want to customize form components and make them suitable for according to the form needs.

Custom trigger verification: In some cases, there is no need for real-time validation of the form data. You can customize the way the control is validated and configure the checkTrigger parameter. 

The default option of checkTrigger is ‘change’ it triggers verification on a change of data. It also includes: 

  1. ‘blur’: Trigger verification when components blur
  2. ‘none’: It is valid when the check method of the form is called

Dynamic form validation: This helps to change validations dynamically. This could be better understood, when a form takes 2 input fields namely- start date, and end date. So the Start Date should never be greater than the End Date. In order to avoid coding in Component files, we can make use of Dynamic form validation.

Props and methods used:

Creating React Application and installing rsuite module:

Step 1: Create React App with the following command

npx create-react-app foldername

This may take a few seconds, next,

Step 2: Navigate to the folder, using the terminal

cd foldername

Step 3: After creating the ReactJS application, Install the required module using the following command

npm install rsuite

The project Structure should be as follows:

Project structure

Example 1: In this example, we will illustrate the default check Open the App.js file, in the src folder and write the following code.

Javascript




import { Form, Button, ButtonToolbar, Schema, Panel } from 'rsuite';
  
const { StringType } = Schema.Types;
const model = Schema.Model({
    name: StringType().isRequired('This field is required.'),
    email: StringType()
  
        // Checks for email format on default trigger
        .isEmail('Please enter a valid email address.')
        .isRequired('This field is required.')
});
  
function TextField(props) {
    const { name, label, accepter, ...rest } = props;
    return (
        <Form.Group controlId={`${name}-3`}>
            <Form.ControlLabel>{label} </Form.ControlLabel>
            <Form.Control name={name} accepter={accepter} {...rest} />
        </Form.Group>
    );
}
function App() {
    return (
        <Form model={model}>
            <TextField name="name" label="Username" />
            <TextField name="email" label="Email" />
            <ButtonToolbar>
                <Button appearance="primary" type="submit">
                    Submit
                </Button>
            </ButtonToolbar>
        </Form>
    );
}
ReactDOM.render(<App />, document.getElementById('root'));


To run the application type the following command in the terminal.

npm start

Output:

Default check in form validation

Example 2: In this example, we will use an Asynchronous check. Open the App.js file, in the src folder and write the following code,

Javascript




import React from 'react';
import 'rsuite/dist/rsuite.min.css'
import { Form, Button, ButtonToolbar, 
    Schema, FlexboxGrid } from 'rsuite';
const { StringType } = Schema.Types;
function asyncCheckUsername(name) {
    return new Promise(resolve => {
        setTimeout(() => {
  
            // Add the condition for asynchronous check
            if (name === 'rsuite')
  
            // rsuite will be the already registered name
            {
                resolve(false);
            }
            else {
                resolve(true);
            }
        }, 500);
    })
}
const model = Schema.Model({
    name: StringType().addRule((value) => {
  
        // Check the entered name
        return asyncCheckUsername(value);
  
    }, 'Username already exists')
        .isRequired('This field is required')
})
export default function App() {
    const formRef = React.useRef()
  
  
    const handleSubmit = () => {
        // When handling form submission
        formRef.current.checkAsync().then(result => {
            console.log(result);
        })
    }
    return (
        <FlexboxGrid.Item colspan={12}>
            <FlexboxGrid.Item colspan={12}>
                <Form
                    model={model}
                >
                    <Form.Group controlId="name-2">
                        <Form.ControlLabel>
                            Type a Username 
                        </Form.ControlLabel>
                        <Form.Control checkAsync name="name" 
                            placeholder="Try to enter rsuite" />
                    </Form.Group>
  
                    <ButtonToolbar>
                        <Button appearance="primary" 
                            onClick={handleSubmit}>
                            Submit
                        </Button>
                    </ButtonToolbar>
                </Form>
            </FlexboxGrid.Item>
        </FlexboxGrid.Item>
    )
}


Output:

Asynchronous check

Example 3: Open the App.js file, in the src folder and write the following code,

Javascript




import React from 'react'
import { Form, Schema } from 'rsuite'
import 'rsuite/dist/rsuite.min.css'
const { StringType } = Schema.Types
  
const model = Schema.Model({
    password: StringType()
        .isRequired('This field is required'),
    verifyPassword: StringType()
        .addRule((value, data) => {
            if (value !== data.password) {
                return false
            }
            return true
        },
            'Passwords do not match')
                .isRequired('This field is required')
});
  
// Pass information for the form label and control
// within the form group at once
const TextField = React.forwardRef((props, ref) => {
    const { name, label, accepter, ...rest } = props;
    return (
        <Form.Group controlId={`${name}-4`} ref={ref}>
            <Form.ControlLabel>{label} </Form.ControlLabel>
            <Form.Control name={name} accepter={accepter} {...rest} />
        </Form.Group>
    );
});
  
export default function App() {
    const formRef = React.useRef()
    const [formValue, setFormValue] = React.useState({
        password: '',
        verifyPassword: ''
  
    })
    return (
        <div style={{ margin: 30 }}>
            <Form
                ref={formRef}
                onChange={setFormValue}
                formValue={formValue}
                model={model}
            >
                <TextField name="password" 
                    label="Password" 
                    type="password" 
                    autoComplete="off" />
                <TextField
                    name="verifyPassword"
                    label="Verify password"
                    type="password"
                    autoComplete="off"
                />
            </Form>
        </div>
    )
}


Output:

 Password validation

Example 4: Form validation using the schema-typed library with rsuite Open the App.js file, in the src folder and write the following code.

Javascript




import React from 'react'
import { Button, ButtonToolbar, Form } from "rsuite"
import { SchemaModel, StringType } from "schema-typed"
import 'rsuite/dist/rsuite.min.css'
export default function App() {
  
    // Saving the form information
    // initial value is set to null
    const [formValue, setFormValue] = React.useState({
        name: "",
        email: "",
        textarea: ""
    })
    const formRef = React.useRef()
  
    // Model using schema model to validate
    // the data taken in the form
    const model = SchemaModel({
        name: StringType().isRequired("Enter valid name"),
        email: StringType()
            .isEmail("Please enter valid email address")
            .isRequired("This field is required"),
        textarea: StringType()
            .isRequired("Describe grievance here")
  
            // Validate the grievance textarea
            // with 100 characters only
            .maxLength(100)
    })
  
    // Handling the form submission
    const handleSubmit = () => {
        if (!formRef.current.check()) {
            console.error("Form error")
            return
        }
        alert("Data collected successfully")
        console.log(formValue, "Form data-: ")
    }
  
    return (
        <div style={{ margin: 30 }}>
            {/* handling the form submission */}
            <Form
                ref={formRef}
                model={model}
                onChange={setFormValue}
                onSubmit={handleSubmit}
                fluid>
                <Form.Group controlId="name">
                    <Form.ControlLabel>
                        Full Name
                    </Form.ControlLabel>
                    <Form.Control name="name" />
                    <Form.HelpText tooltip>
                        Please enter Full Name
                    </Form.HelpText>
                </Form.Group>
  
                <Form.Group controlId="email">
                    <Form.ControlLabel>
                        Email
                    </Form.ControlLabel>
                    <Form.Control name="email" />
                    <Form.HelpText tooltip>
                        Please enter email
                    </Form.HelpText>
                </Form.Group>
  
                <Form.Group controlId="textarea">
                    <Form.ControlLabel>
                        Enter grievance here
                    </Form.ControlLabel>
                    <Form.Control name="textarea" rows={5} />
                </Form.Group>
                <ButtonToolbar>
                    <Button appearance='primary' type="submit">
                        Submit
                    </Button>
                </ButtonToolbar>
            </Form>
        </div>
    )
}


Output:

Form validation using the schema-typed library

Reference: https://rsuitejs.com/components/form-validation/



Last Updated : 21 Feb, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads