How can I help you?
React functional component in React Form validator component
21 Feb 202619 minutes to read
This article provides step-by-step instructions on using React Hooks in an HTML form with the FormValidator component.
The following is a list of React Hooks methods to utilize while performing form validation.
| Hooks | Description |
|---|---|
useState |
A Hook that allows you to define state in functional components. Returns a state variable and a function to update it. |
useEffect |
A Hook that executes code after the component renders and re-renders. |
useRef |
A Hook that creates a direct reference to a DOM element within the functional component. |
useReducer |
A Hook that accepts a reducer function and initial state, returning a state value and a dispatch function for actions. |
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, add Syncfusion® form components to create a simple form.
In the following example, a login form is created using Syncfusion® components such as TextBox, DatePicker, and Button, and validated with the FormValidator component.
-
TextBox- Collects the user’s email and password -
DatePicker- Collects the user’s date of birth
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;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
To validate the input, specify rules for the email, password, and date of birth fields. Form validation is initiated using the useEffect Hook.
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.
The useState Hook stores the value of the date of birth field.
const [dateOfBirth, setDateOfBirth] = useState('');The useReducer Hook updates the email and password state values.
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);The useRef Hook focuses the username field on initial load.
const userNameRef = useRef(null);
useEffect(() => {
userNameRef.current.focusIn();
}Run the Application
Run the application in the browser using the following command.
npm run start