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
- Class Component Syntax:
React.componentshould beReact.Component(capitalized "Component" is required for React class components) - Naming Consistency: Switched
LastNametolastNameandvalidatefirstNametovalidateFirstNameto follow JavaScript camelCase conventions - Validation Key Uniformity: Fixed inconsistent key names (
validateStatusvsvalidationStatus) in your validation functions - Error Display: Added span elements under each input to show error messages only when validation fails
- Better Validation Logic: Added
trim()to ignore whitespace-only inputs, and fixed punctuation in error messages - 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
onChangehandler callshandleInputChange, 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 (ornullif 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
相关产品推荐
相关产品推荐

