3

I'm trying to implement authentification system with express + node js. So far it's been good, but now I see that even when I refresh the page, the form submits to the server. This is how my code looks like:

Client side:

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>)
}

Server side:

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 I'm looking to submit the form only if validate.form(username, email, password, confirm) returns true. I'm using bodyParser as module to parse the json!

Razvan Alex
  • 1,706
  • 2
  • 18
  • 21
  • Do not name a function `submit`, nor use `this.submit` in a form like that, use proper event handlers with `addEventListener` – adeneo Oct 16 '16 at 14:10
  • Possible duplicate of http://stackoverflow.com/questions/5651933/what-is-the-opposite-of-evt-preventdefault – leroydev Oct 16 '16 at 14:18

1 Answers1

1

Assuming that form.validate() is synchronous, you should call preventDefault only if form.validate() returns the error string.

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.
}
Gab
  • 491
  • 3
  • 6
  • Right now I'm not home to test it, but this should be working. Meanwhile I made some changes and I think I'm gonna use the validation method on the server side, ty – Razvan Alex Oct 16 '16 at 16:03