Javascript 如何仅在条件为真时提交表格
我正在尝试用express+NodeJS实现身份验证系统。到目前为止还不错,但现在我看到,即使在刷新页面时,表单也会提交到服务器。我的代码是这样的: 客户端:Javascript 如何仅在条件为真时提交表格,javascript,express,Javascript,Express,我正在尝试用express+NodeJS实现身份验证系统。到目前为止还不错,但现在我看到,即使在刷新页面时,表单也会提交到服务器。我的代码是这样的: 客户端: submit(e) { let data = this.state; /// object with user's informations e.preventDefault() validate.form(this.state.username, this.state.email, this.state.pass
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>)
}
TL;DR我只希望在validate.form(用户名、电子邮件、密码、确认)返回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.
}
不要给函数命名
submit
,也不要使用this。以这样的形式提交
,使用合适的事件处理程序和addEventListener
可能的副本,我现在不在家测试它,但这应该可以工作。同时我做了一些修改,我想我会在服务器端使用验证方法,泰
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.
}