javascript - 反应表单验证
问题描述
我刚刚开始学习反应,我正在做一个简单的表单应用程序。我的问题是如何验证文本和电子邮件输入?我尝试了几种方法,但是代码变得非常混乱,所以我删除了带有“验证”的代码
这是我的代码这是我的父“表单”组件
import React, { Component } from "react";
import Name from "components/Name";
import Email from "components/Email";
import Select from "components/Select";
import Bio from "components/Bio";
// Create Form Component
class Form extends Component {
constructor(props) {
super(props);
this.state = {
firstName: "",
lastName: "",
email: "",
country: "Norway",
bio: ""
};
}
// Handle inputs value on change event
handleChange = event => {
this.setState({
[event.target.id]: event.target.value
});
};
// Handle the form submission
handleSubmit = event => {
event.preventDefault();
// Send POST Request (every postbin expires aftre 30min)
fetch("https://postb.in/1580328526126-6915104780346", {
method: "POST",
mode: "no-cors",
headers: {
"Content-Type": "application/json",
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Headers": "*"
},
body: JSON.stringify(this.state)
});
console.log(this.state);
// Clear form inputs
this.setState({
firstName: "",
lastName: "",
email: "",
country: "",
bio: ""
});
};
// Render Form Component and its child components
render() {
// Destructuring the current component state
const { firstName, lastName, email, country, bio } = this.state;
return (
<form onSubmit={this.handleSubmit}>
<div className="shape rectangle"></div>
<div className="shape triangle"></div>
<div className="shape circle"></div>
<Name
firstName={firstName}
lastName={lastName}
handleChange={this.handleChange}
/>
<Email email={email} handleChange={this.handleChange} />
<Select country={country} handleChange={this.handleChange} />
<Bio bio={bio} handleChange={this.handleChange} />
<button type="submit" className="btn">
Submit
</button>
</form>
);
}
}
export default Form;
这是一个子组件,其余子组件与此类似。
import React, { Component } from "react";
// Create Name component for name && email inputs
class Name extends Component {
// Render labels and name inputs
render() {
const { firstName, lastName, handleChange } = this.props;
return (
<div className="form-names">
<label htmlFor="firstName">Name</label>
<br />
<input
type="text"
name="firstName"
value={firstName}
placeholder="First Name"
id="firstName"
onChange={handleChange}
required
/>
<input
type="text"
name="lastName"
value={lastName}
placeholder="Last Name"
id="lastName"
onChange={handleChange}
required
/>
</div>
);
}
}
export default Name;
解决方案
有一些库可用于在 react 中进行表单验证。基本上,您将只有一个表单验证功能,该功能使用这些库支持的正则表达式比较和条件等内容。上面的链接提供了与一些流行库的比较。
推荐阅读
- ajax - 当jsp中发生ajax调用时,如何从控制器获取数据到jsp?
- java - 如何在弹簧靴中有条件地自动装配?
- c# - 如何在 SQL 选择查询中添加参数?
- varnish - Varnish Request Url 与 apache 请求不同
- office-ui-fabric - Office UI Fabric React Word Addin 某些图标未显示
- database - 如何找到前 10 名昂贵的 sql -Oracle
- c# - 是否有用于浏览重载方法的 Visual Studio 功能?
- kotlin - 找不到流量的合同附件
- azure-devops - 如何将工件标记为“由 QA 验证”?
- sql - 我可以永久更改 SQL Server 表的日期格式吗?