React technical principles and code development practice: React form processing and verification

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:

  1. HTML5 Constraint Validation API
  2. React useState() hook
  3. React forms with validation
  4. Form element types and attributes
  5. Validation functions in React
  6. Complex form validation with multiple fields
  7. Handling server-side errors with fetch()
  8. Submitting the form with JavaScript or a button click event
  9. 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

Wrap the tag and add the required attribute to each input box that needs to be validated. For example:

<form onSubmit={this.handleSubmit}>
  <label htmlFor="name">Name:</label>
  <input id="name" name="name" type="text" value={name} onChange={this.handleChange} required/>

  <label htmlFor="age">Age:</label>
  <input id="age" name="age" type="number" value={age} onChange={this.handleChange} required/>

  <button type="submit">Submit</button>
</form>

If you want to implement form validation yourself, you need to validate the input value in the handleChange() method and set the error message through the setErrors() function. For example:

handleValidation = (event) => {
  const target = event.target;
  if (!target.checkValidity()) {
    this.setState({
      isFormValid: false,
      errors: {
       ...this.state.errors,
        [target.name]: target.validationMessage || "Invalid Value",
      },
    });
  } else {
    this.setState((prevState) => ({
      isFormValid: true,
      errors: {
       ...prevState.errors,
        [target.name]: "",
      },
    }));
  }
};

handleChange = (event) => {
  const target = event.target;
  let value = target.value;

  switch (target.type) {
    case "number":
      value = Number(value);
      break;

    default:
      break;
  }

  this.setState((prevState) => ({
    formData: {
     ...prevState.formData,
      [target.name]: value,
    },
  }));
};

The handleChange() function converts the input value according to different types to ensure that it is in numeric format. In the handleValidation() function, we call the checkValidity() method to check whether the input value is valid. If it is invalid, set the error message, otherwise clear the error message. If the error message is not empty, the form is considered invalid. The handleChange() function is responsible for updating the formData object.

Form element types and attributes

HTML form element types and their attributes:

Element Type Attributes Description
Text type, required, disabled Allows users to enter text data into an input field. The type attribute specifies what kind of data can be entered, such as email, password, number, etc. The required attribute specifies that the user must provide a value before submitting the form. The disabled attribute prevents users from editing the input field.