【发布时间】:2021-10-28 07:22:24
【问题描述】:
我有一个登录页面,我需要验证 gmail 的输入,即。名称应为 gmail 格式。我很确定函数的逻辑可以正常工作,但是在声明和调用函数的部分存在一些问题。这是我的代码:
const Login = () => {
// const [name,setName] = useState('Shakthi Saravanan');
// const {data:blogs, isPending, error} = useFetch('http://localhost:8000/blogs');
function handleChange(field, e) {
let fields = this.state.fields;
fields[field] = e.target.value;
this.setState({ fields });
}
function handleValidation() {
let fields = this.state.fields;
let errors = {};
let formIsValid = true;
//Name
if (!fields["name"]) {
formIsValid = false;
errors["name"] = "Cannot be empty";
}
if (typeof fields["name"] !== "undefined") {
if (!fields["name"].match(/^[a-zA-Z]+$/)) {
formIsValid = false;
errors["name"] = "Only letters";
}
}
//Email
if (!fields["email"]) {
formIsValid = false;
errors["email"] = "Cannot be empty";
}
if (typeof fields["email"] !== "undefined") {
let lastAtPos = fields["email"].lastIndexOf("@");
let lastDotPos = fields["email"].lastIndexOf(".");
if (
!(
lastAtPos < lastDotPos &&
lastAtPos > 0 &&
fields["email"].indexOf("@@") == -1 &&
lastDotPos > 2 &&
fields["email"].length - lastDotPos > 2
)
) {
formIsValid = false;
errors["email"] = "Email is not valid";
}
}
this.setState({ errors: errors });
return formIsValid;
}
return (
<div className="login-cot bg-danger" id="layoutAuthentication">
<div id="layoutAuthentication_content">
<main>
<div className="container ">
<div className="row justify-content-center ">
<div className="col-lg-5 ">
<div className="card shadow-lg border-0 rounded-lg mt-5 bg-secondary">
<center><h1 className="bg-warning" style={{padding:"10px",}}><b><BsBugFill /><BsTools /> <BsColumns /> BFP</b></h1></center>
<div className="card-header"><h3 className="text-center my-1"><b>Login</b></h3></div>
<div className="card-body">
<form>
<div className="form-floating mb-3">
<input className="form-control" id="inputEmail" type="email"
onChange={this.handleChange.bind(this, "name")} placeholder="name@example.com"
value={this.state.fields["name"]} />
<label for="inputEmail">Email address</label>
</div>
<div className="form-floating mb-3">
<input className="form-control" id="inputPassword" type="password" placeholder="Password" />
<label for="inputPassword">Password</label>
</div>
<div className="d-flex align-items-center justify-content-between mt-4 mb-0">
<Link className="small text-light" to="/forgotPassword">Forgot Password?</Link>
<Link className="btn btn-success" to="/home">Login</Link>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
</main>
</div>
</div>
);
}
但是我遇到了一个错误:
请帮忙
【问题讨论】:
标签: javascript reactjs validation