1. Background Introduction
Currently, front-end technology is changing with each passing day, and new technologies are emerging one after another. React, as the most popular Javascript library at the moment, is increasingly favored by developers. React is known as “the Facebook of JavaScript”. Its advantages include componentization, declarative programming, JSX syntax, etc., and React Hooks are also a disruptive update. This series of articles will start with the basic concepts and usage of React technology, guide readers to master React technology step by step, and carry out complex form validation applications on this basis. What is a form? A form is an area on a page used to collect user input data. Commonly used forms in web pages include input (text box), textarea (multi-line text input box), select (drop-down menu selection box), checkbox (check box), radio (radio button), etc. The data in the form needs to be checked and stored either on the server side or in a local database. The traditional form verification method generally uses the client to perform verification, that is, using JavaScript code to check the data on the browser side. But the limitations of this approach are obvious-it cannot prevent malicious attacks. Therefore, more and more websites are beginning to use back-end verification, that is, the server verifies the data after submitting the form data to the server, which can better protect the security of users’ private information. But at the same time, introducing back-end verification will also bring some problems. For example, poor user experience, heavy development workload, etc. Therefore, how to implement pure client-side form validation in the React framework has become a difficult problem faced by React developers. First, we should understand the new attributes in HTML5. Among the new features of HTML5 is an API called “Constraint Validation API”. It allows developers to validate input values of HTML form elements on the client side and display corresponding error messages. React can also implement form validation with the help of this API. Secondly, since React is based on virtual DOM, which is different from the DOM structure rendered in the browser, form verification requires responsive programming and DOM nodes cannot be directly manipulated. However, the useState() hook provided by React can help us solve this problem. Finally, this article focuses on the relevant knowledge of React form validation. The main contents include:
- HTML5 Constraint Validation API
- React useState() hook
- React forms with validation
- Form element types and attributes
- Validation functions in React
- Complex form validation with multiple fields
- Handling server-side errors with fetch()
- Submitting the form with JavaScript or a button click event
- Preserving user input on page refresh
The above is the table of contents of this series of articles, and subsequent content will be added gradually. I hope everyone can participate in the writing of the article and jointly promote the progress of React technology! Reprinting, excerpts and comments are welcome, just indicate the author’s name!
2. Core concepts and connections
The form verification process can be divided into the following steps:
- User input data
- Data validation
- Data submission (optional)
- Data saving
Among them, the second step is usually processed by the back-end service, while the first three steps can be completed on the client.
HTML5 Constraint Validation API
One of the new features in HTML5 is the constraint validation API, which allows developers to validate the values of HTML form elements on the client side. The API defines multiple verification types and corresponding methods. If an element has certain validation rules set, then it will trigger the corresponding validation method. For example, the email verification type corresponds to the checkValidity() method, which checks whether it conforms to the email format; the pattern verification type corresponds to the setCustomValidity() method, which can customize the error message when verification fails. For example, in React, the verification of form element values can be triggered through the onChange event. For example: , where the handleValidation() function is responsible for verifying the input value. You can also manually bind event listeners through the addEventListener() method. For elements such as checkbox, radio, and select, you can use attributes such as validity.valueMissing and validity.typeMismatch to determine whether their values are valid. In addition to the constraint validation API provided by HTML5, React also provides a way to customize validation functions. This type of function can perform any logical judgment on the value entered by the user and return a Boolean value to indicate whether the verification is passed.
React useState() hook
The useState() hook allows us to manage state variables inside React components, and it makes re-rendering of components very simple. useState() returns an array, the first element is the current state, and the second element is the function that updates the state. for example:
const [count, setCount] = useState(0);
This code declares a state variable named count with an initial value of 0. The setCount() function is used to modify the status. However, React recommends that we not modify the state directly, but update the state through the setState() function. As follows:
setCount(count + 1); // Modify the status to count + 1
This code actually calls the setState() function and passes in an object { count: count + 1 } to update the state. Here, count + 1 represents the new status value. Note: Do not rely on the return value of useState() in conditional statements, as it may return different results on each render. The correct approach is to read the return value of useState() in componentDidMount() or componentDidUpdate(), and then compare the conditional statements.
React forms with validation
In React, if we want to use the HTML5 constraint validation API to implement form validation, we can directly