如果条件为真,如何提交表格

时间:2016-10-16 14:07:18

标签: javascript express

我正在尝试使用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(用户名,电子邮件,密码,确认)返回true时才提交表单。我正在使用bodyParser作为解析json的模块!

1 个答案:

答案 0 :(得分:0)

假设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.
}