gpt4 book ai didi

javascript - 如何仅在条件为真时提交表单

转载 作者:行者123 更新时间:2023-12-01 16:37:40 25 4
gpt4 key购买 nike

我正在尝试使用 express + node js 实现身份验证系统。到目前为止一切都很好,但现在我发现即使刷新页面,表单也会提交给服务器。这是我的代码的样子:

客户端:

submit(e) {
let data = this.state; /// object with user's informations
e.preventDefault()
validate.form(this.state.username, this.state.email, this.state.password, this.state.confirm) // this returns true if everything is fine or returns the error string!

}

render() {
return (<div>
<form action="/login" onSubmit = {this.submit} method="post">
<p>Username:</p>
<input type="text" onChange = {this.getData} name="username" value = {this.state.username} />
<p>Email</p>
<input type="text" onChange={this.getData} name = "email" value = {this.state.email} />
<p>Password</p>
<input type="text" onChange={this.getData} name = "password" value = {this.state.password} />
<p>Confirm Password</p>
<input type="text" onChange={this.getData} name = "confirm" value = {this.state.confirm} />
<br/> <br/>
<input type="Submit" value='Submit' /> ///this is not working!
</form>
</div>)
}

服务器端:

app.post('/login',(req, res) => {
console.log(req.body)
res.sendFile(__dirname + '/src/index.html')
db.query('INSERT INTO users SET ?', req.body, (err, res) => console.log("done!"))

})

TL;DR 我希望只有在 validate.form(username, email, password, confirm) 返回 true 时才提交表单。我正在使用 bodyParser 作为模块来解析 json!

最佳答案

假设 form.validate() 是同步的,您应该仅在 form.validate() 返回错误字符串时调用 preventDefault。

submitForm(e) { // avoid to use 'submit' as method name

let data = this.state; /// object with user's informations
let formValid = validate.form(this.state.username, this.state.email, this.state.password, this.state.confirm);

if(formValid !== true) {
e.preventDefault()
}

// else, if formValid is true, the default behaviour will be executed.
}

关于javascript - 如何仅在条件为真时提交表单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40071203/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com