Search results

React functional component in React Form Validator component

08 Dec 2022 / 4 minutes to read

This article provides a step-by-step instructions on using the React functional Hooks in a simple HTML form with the FormValidator component.

The following is a list of React Hooks methods to utilize while performing form validation.

Hooks Description
useState The useState is a Hook that allows the state to be defined in the functional components. If the initial state is passed to this function, then it will return a state variable with a value and a function to update this state value.
useEffect The useEffect is a Hook that executes code after rendering and re-rendering the component.
useRef The useRef is a Hook function that allows the functional component to create a direct reference to the DOM element.
useReducer The useReducer is a Hook function that accepts a reducer function and an initial state as arguments. It returns a state value and another function to dispatch an action.

Create a React form with Syncfusion form components

To create a React application with Syncfusion components, refer to the Getting Started section. Once the application is set up, replace the components with React form and Syncfusion form components to create a simple form.

In the following example, a login form is created with Syncfusion components such as TextBox, DatePicker, and Button. This form is validated using the React FormValidator component.

  • TextBox - To get the user’s email and password
  • DatePicker - To get the user’s date of birth
Source
Preview
App.jsx
App.tsx
Copied to clipboard
import { useState, useEffect, useRef, useReducer } from 'react';
import * as React from "react";
import { ButtonComponent } from '@syncfusion/ej2-react-buttons';
import { FormValidator } from '@syncfusion/ej2-inputs';
import { TextBoxComponent } from '@syncfusion/ej2-react-inputs';
import { DatePickerComponent } from '@syncfusion/ej2-react-calendars';
let formObject;
function App() {
    const userNameRef = useRef(null);
    const [dateOfBirth, setDateOfBirth] = useState('');
    const initialState = { email: '', password: '' };
    const reducer = (state, action) => {
        switch (action.type) {
            case 'update':
                return { ...state, [action.field]: action.value };
            default:
                return initialState;
        }
    };
    const [state, dispatch] = useReducer(reducer, initialState);
    const dateChangeHandler = (event) => {
        setDateOfBirth(event.value);
    };
    const update = (field) => (event) => {
        //update action is dispatched to update the email and password state value
        dispatch({ type: 'update', field, value: event.value });
    };
    useEffect(() => {
        userNameRef.current.focusIn();
        const options = {
            // validation rules
            rules: {
                email: {
                    required: [true, '* Please enter your email'],
                },
                password: {
                    required: [true, '* Please enter your password'],
                },
                date: {
                    required: [true, '* Please enter your date of birth'],
                },
            },
        };
        // Initialize the form validator
        formObject = new FormValidator('#form1', options);
    }, []);
    const onSubmit = () => {
        formObject.validate();
        if (formObject.validate()) {
            formObject.element.reset();
        }
    };
    return (<div>
  <div className="control_wrapper" id="control_wrapper">
    <h3 className="form-title">User Login</h3>
    <div className="control_wrapper textbox-form">
      <form id="form1" method="post">
        <div className="form-group">
          <TextBoxComponent ref={userNameRef} type="email" name="email" value={state.email} change={update('email')} placeholder="Username" floatLabelType="Auto" data-msg-containerid="errroForEmail"/>
          <div id="errroForEmail"/>
        </div>
        <div className="form-group">
          <TextBoxComponent type="password" name="password" value={state.password} change={update('password')} placeholder="Password" floatLabelType="Auto" data-msg-containerid="errroForPassword"/>
          <div id="errroForPassword"/>
        </div>
        <div className="form-group">
          <DatePickerComponent name="date" value={dateOfBirth} change={dateChangeHandler} placeholder="Date of Birth" floatLabelType="Auto" data-msg-containerid="errroForDateOfBirth"/>
          <div id="errroForDateOfBirth"/>
        </div>
      </form>
      <div className="submitBtn">
        <ButtonComponent onClick={onSubmit}>Submit</ButtonComponent>
      </div>
    </div>
    <br />
    <br />
  </div>
</div>);
}
export default App;
Copied to clipboard
import { useState, useEffect, useRef, useReducer } from 'react';
import * as React from "react";
import { ButtonComponent } from '@syncfusion/ej2-react-buttons';
import { FormValidator } from '@syncfusion/ej2-inputs';
import { TextBoxComponent } from '@syncfusion/ej2-react-inputs';
import { DatePickerComponent } from '@syncfusion/ej2-react-calendars';

let formObject;
function App() {
  const userNameRef = useRef(null);
  const [dateOfBirth, setDateOfBirth] = useState('');
  const initialState = { email: '', password: '' };
  const reducer = (state, action) => {
switch (action.type) {
  case 'update':
    return { ...state, [action.field]: action.value };

  default:
    return initialState;
}
  };
  const [state, dispatch] = useReducer(reducer, initialState);

  const dateChangeHandler = (event) => {
setDateOfBirth(event.value);
  };

  const update = (field) => (event) => {
//update action is dispatched to update the email and password state value
dispatch({ type: 'update', field, value: event.value });
  };

  useEffect(() => {
userNameRef.current.focusIn();
const options = {
  // validation rules
  rules: {
    email: {
      required: [true, '* Please enter your email'],
    },
    password: {
      required: [true, '* Please enter your password'],
    },
    date: {
      required: [true, '* Please enter your date of birth'],
    },
  },
};
// Initialize the form validator
formObject = new FormValidator('#form1', options);
  }, []);

  const onSubmit = () => {
formObject.validate();
if (formObject.validate()) {
  (formObject as any).element.reset();
}
  };

  return (
<div>
  <div className="control_wrapper" id="control_wrapper">
    <h3 className="form-title">User Login</h3>
    <div className="control_wrapper textbox-form">
      <form id="form1" method="post">
        <div className="form-group">
          <TextBoxComponent
            ref={userNameRef}
            type="email"
            name="email"
            value={state.email}
            change={update('email')}
            placeholder="Username"
            floatLabelType="Auto"
            data-msg-containerid="errroForEmail"
          />
          <div id="errroForEmail" />
        </div>
        <div className="form-group">
          <TextBoxComponent
            type="password"
            name="password"
            value={state.password}
            change={update('password')}
            placeholder="Password"
            floatLabelType="Auto"
            data-msg-containerid="errroForPassword"
          />
          <div id="errroForPassword" />
        </div>
        <div className="form-group">
          <DatePickerComponent
            name="date"
            value={dateOfBirth}
            change={dateChangeHandler}
            placeholder="Date of Birth"
            floatLabelType="Auto"
            data-msg-containerid="errroForDateOfBirth"
          />
          <div id="errroForDateOfBirth" />
        </div>
      </form>
      <div className="submitBtn">
        <ButtonComponent onClick={onSubmit}>Submit</ButtonComponent>
      </div>
    </div>
    <br />
    <br />
  </div>
</div>
  );
}
export default App;

Perform validation

For the input validation, specify rules for the email, password, and date of birth fields. The form validation will be initiated using the useEffect Hook.

Copied to clipboard
useEffect(() => {
    const options = {
        // add the rules for validation
        rules: {
            email: {
                required: [true, '* Please enter your email'],
            },
            password: {
                required: [true, '* Please enter your password'],
            },
            date: {
                required: [true, '* Please enter your date of birth'],
            },
        }
    };
    // initialize the form validator
    this.formObject = new FormValidator('#form1', options);
}, []);

Check out the validation rules section to learn more about the validation rules.

Here, the useState Hook is used to store the value of the date of birth field.

Copied to clipboard
const [dateOfBirth, setDateOfBirth] = useState('');

The useReducer Hook is used to update the email and password state values.

Copied to clipboard
const initialState = { email: '', password: '' };

const reducer = (state, action) => {
    switch (action.type) {
        case 'update':
            return { ...state, [action.field]: action.value };
        default:
            return initialState;
    }
};

const [state, dispatch] = useReducer(reducer, initialState);

Here, the useRef Hook is used to focus the username field at initial loading.

Copied to clipboard
const userNameRef = useRef(null);
useEffect(() => {
    userNameRef.current.focusIn();
}

Run the Application

Run the application in the browser using the following command.

Copied to clipboard
npm run start