You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React新手求助:完善表单输入校验功能(附代码)

Hey there! No worries at all—we all start somewhere with React. Let's fix up your form component to get that validation working properly, step by step.

First, I'll point out a few small issues in your original code, then share the full corrected version with explanations:

Key Fixes & Improvements

  1. Class Component Syntax: React.component should be React.Component (capitalized "Component" is required for React class components)
  2. Naming Consistency: Switched LastName to lastName and validatefirstName to validateFirstName to follow JavaScript camelCase conventions
  3. Validation Key Uniformity: Fixed inconsistent key names (validateStatus vs validationStatus) in your validation functions
  4. Error Display: Added span elements under each input to show error messages only when validation fails
  5. Better Validation Logic: Added trim() to ignore whitespace-only inputs, and fixed punctuation in error messages
  6. Basic Styling: Added simple inline styles to make the form layout cleaner

Full Corrected Code

import React from "react";

class Form extends React.Component {
  state = {
    firstName: { value: "", validateStatus: "", errorMsg: null },
    lastName: { value: "", validateStatus: "", errorMsg: null }
  };

  handleInputChange = (e, validationFun) => {
    const target = e.target;
    const inputName = target.name;
    const inputValue = target.value;
    const validationResult = validationFun(inputValue);

    this.setState({
      [inputName]: { value: inputValue, ...validationResult }
    });
  };

  validateFirstName = (firstName) => {
    if (!firstName.trim()) {
      return { validateStatus: "error", errorMsg: "First Name may not be empty" };
    } else if (firstName.length > 12) {
      return { validateStatus: "error", errorMsg: `First Name is too long - 11 characters allowed.` };
    } else {
      return { validateStatus: "success", errorMsg: null };
    }
  };

  validateLastName = (lastName) => {
    if (!lastName.trim()) {
      return { validateStatus: "error", errorMsg: "Last Name may not be empty" };
    } else if (lastName.length > 12) {
      return { validateStatus: "error", errorMsg: `Last Name is too long - 11 characters allowed.` };
    } else {
      return { validateStatus: "success", errorMsg: null };
    }
  };

  render() {
    return (
      <div style={{ padding: "20px" }}>
        <div style={{ marginBottom: "15px" }}>
          <label style={{ display: "block", marginBottom: "5px" }}>First Name</label>
          <input
            type="text"
            name="firstName"
            value={this.state.firstName.value}
            onChange={(event) => this.handleInputChange(event, this.validateFirstName)}
            style={{ padding: "8px", width: "300px" }}
          />
          {this.state.firstName.validateStatus === "error" && (
            <span style={{ color: "#ff4d4f", display: "block", marginTop: "5px" }}>
              {this.state.firstName.errorMsg}
            </span>
          )}
        </div>
        <div>
          <label style={{ display: "block", marginBottom: "5px" }}>Last Name</label>
          <input
            type="text"
            name="lastName"
            value={this.state.lastName.value}
            onChange={(event) => this.handleInputChange(event, this.validateLastName)}
            style={{ padding: "8px", width: "300px" }}
          />
          {this.state.lastName.validateStatus === "error" && (
            <span style={{ color: "#ff4d4f", display: "block", marginTop: "5px" }}>
              {this.state.lastName.errorMsg}
            </span>
          )}
        </div>
      </div>
    );
  }
}

export default Form;

How It Works

  • When a user types in an input, the onChange handler calls handleInputChange, which updates the input's value in state and runs the corresponding validation function
  • The validation function returns an object with a status (error/success) and an error message (or null if valid)
  • In the render method, we check if the input's validation status is error—if so, we display the error message in a red span below the input

内容的提问来源于stack exchange,提问作者Mojo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 07:58:41