0

so i just finishing preparing a form with node js and react js, when i tried it with Postman to add a user, it was working perfectly with the validations and everything but then i tried to link it to my font end and it didn't work, the problem is if i enter a true data, it will be added to my database and it moves to the next page, and when i enter a wrong data, it won't be added to my backend but it will still move to the next page !

node js userModel.js 
const mongoose = require('mongoose')
const bcrypt = require('bcrypt')
const saltRounds = (10)
const schema = mongoose.Schema



const userSchema = new mongoose.Schema({
    nom: {
        type: String,
        required: true
    },
    prenom: {
        type: String,
        required: true,
        trim: true // read the spaces
    },
    email: {
        type: String,
        required: true,
        validate: {
            validator: function ValidateEmail(v) {
                if (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(v)) //w{2,3} lazemha tkoun fila5er .org .com .tn ya3ni . w ba3édha 7aja tetkawén par 2 ou 3 caractéres
                {
                    return (true)
                }
                console.log("You have entered an invalid email address!")
                return (false)
            }
        }
    },
    password: {
        type: String,
        required: true,
        validate: {
            validator: function password1(number){
          var phoneno =/^[A-Za-z]\w{7,14}$/;
          if(phoneno.test(number)){
              return true
            } else {
                console.log("invalid password");
                return false}
            }
        }
    },
    phone: {
        type: String,
        required: true
        /*validate: {
            validator: function phonenumber(number) {
                var phoneno = /^\d{10}$/; //il faut utiliser un nombre a 10 chiffres sans virgule,ni espace
                if (phoneno.test(number)) {
                    return true
                } else {
                    console.log("invalid number");
                    return false
                }
            }
        }*/
    }
    //order: [{
    //type: schema.Types.ObjectId,
    //ref: 'order'
    //}],
    //photo: {
        //type: String
    //}
});

userSchema.pre('save', function(next) {
    this.password = bcrypt.hashSync(this.password, saltRounds);
    next();
})

module.exports = mongoose.model('user', userSchema)

react js gate.js

import axios from 'axios';
import React, { Component } from 'react'



class Gate extends Component {
    constructor(){
        super()
        this.state={
            name:'',
            lastname:'',
            email:'',
            phone:'',
            password:''
        }  
    }
    validate = ()=>{
        var isError = false;
        const errors = {
            emailErr:'',
            passwordErr:'',
        }
        const regex2=/^[A-Za-z]\w{7,14}$/;
        const regex1=/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/;
        if((this.state.password === '')||(this.state.password.length>10)||!regex2.test(this.state.password)){
            isError = true;
            errors.passwordErr = 'verifier votre password'
        }
        if((this.state.email === '')||(this.state.email.length>5)||!regex1.test(this.state.email)){
            isError= true;
            errors.emailErr = 'verifier votre email'
        }
        if(isError){
            this.setState({
                ...this.state,
                ...errors
            })
        }

    }
    envoyer(){
    
        let err = this.validate()
        if(!err){
            axios.post("http://localhost:3050/users/addUser",{
                nom:this.state.name,
                prenom:this.state.lastname,
                email:this.state.email,
                password:this.state.password,
                phone:this.state.phone
            })
            .then(res=>{
                console.log('data',res.data)
                window.location.href='/app/dashboard'
            })
        }
        
    }


    render() {
        console.log(this.state.name)
        console.log(this.state.email)
        console.log(this.state.password)

        return ( 
        <div>
            <form action="">
            <label for="fname">First name:</label><br/>
            <input type="text" id="fname" name="fname" onChange={event=>this.setState({name:event.target.value})} /><br/>
            <label for="lname">Last name:</label><br/>
            <input type="text" id="lname" name="lname" onChange={event=>this.setState({lastname:event.target.value})} /><br/>
            <label for="Email">Email:</label><br/>
            <input type="email" id="email" name="email" onChange={event=>this.setState({email:event.target.value})} />
            {<div style={{fontSize:12,color:'red'}}>{this.state.emailErr}</div>}
            <label for="phone">phone:</label><br/>
            <input type="text" id="phone" name="lname" onChange={event=>this.setState({phone:event.target.value})} /><br/>
            <label for="password">password:</label><br/>
            <input type="password" id="password" name="lname" onChange={event=>this.setState({password:event.target.value})} />
            {<div style={{fontSize:12,color:'red'}}>{this.state.passwordErr}</div>}
            <br/>
            
            <input type="submit" value="Sign In" onClick={()=>{this.envoyer()}} />
            </form>
        </div>
        );
    }
}


export default Gate
           

Please help me !

1 Answer 1

1

Return the error from your validate method.

Working example here => https://stackblitz.com/edit/react-zfwvuh?file=src%2FApp.js

import React, { Component } from "react";

class Gate extends Component {
  constructor() {
    super();
    this.state = {
      name: "",
      lastname: "",
      email: "",
      phone: "",
      password: "",
      emailErr: "",
      passwordErr: ""
    };
  }

  validate = () => {
    const errors = {
      emailErr: null,
      passwordErr: null
    };

    const regex2 = /^[A-Za-z]\w{7,14}$/;
    const regex1 = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/;

    if (this.state.password.length > 10) {
      errors.passwordErr = "verifier votre password";
    }

    if (!regex1.test(this.state.email)) {
      errors.emailErr = "verifier votre email";
    }

    return errors;
  };

  envoyer = e => {
    e.preventDefault();

    const errors = this.validate();

    if (errors.emailErr || errors.passwordErr) {
      this.setState({ ...errors });
    } else {
      console.log("data to be send", this.state);
    }
    // if (!err) {
    //   axios
    //     .post("http://localhost:3050/users/addUser", {
    //       nom: this.state.name,
    //       prenom: this.state.lastname,
    //       email: this.state.email,
    //       password: this.state.password,
    //       phone: this.state.phone
    //     })
    //     .then(res => {
    //       console.log("data", res.data);
    //       window.location.href = "/app/dashboard";
    //     });
    // }
  };

  render() {
    return (
      <div>
        <form>
          <label for="fname">First name:</label>
          <br />
          <input
            type="text"
            id="fname"
            name="fname"
            onChange={event => this.setState({ name: event.target.value })}
          />
          <br />
          <label for="lname">Last name:</label>
          <br />
          <input
            type="text"
            id="lname"
            name="lname"
            onChange={event => this.setState({ lastname: event.target.value })}
          />
          <br />
          <label for="Email">Email:</label>
          <br />
          <input
            type="email"
            id="email"
            name="email"
            onChange={event =>
              this.setState({ email: event.target.value, emailErr: null })
            }
          />
          {
            <div style={{ fontSize: 12, color: "red" }}>
              {this.state.emailErr}
            </div>
          }
          <label for="phone">phone:</label>
          <br />
          <input
            type="text"
            id="phone"
            name="lname"
            onChange={event => this.setState({ phone: event.target.value })}
          />
          <br />
          <label for="password">password:</label>
          <br />
          <input
            type="password"
            id="password"
            name="lname"
            onChange={event =>
              this.setState({ password: event.target.value, passwordErr: null })
            }
          />
          {
            <div style={{ fontSize: 12, color: "red" }}>
              {this.state.passwordErr}
            </div>
          }
          <br />

          <input type="submit" value="Sign In" onClick={this.envoyer} />
        </form>
      </div>
    );
  }
}

export default Gate;

Sign up to request clarification or add additional context in comments.

9 Comments

I think this pretty much is the problem too
Hello, i tried that and it didn't work.. the form stopped submiting the false and true data
If i enter wrong data, the form won't be submited and nothing will be added to the database, but if enter true validated dated, the data will be added to the database but it will stay on the same page
If I enter the wrong data, the form won't be submitted and nothing will be added to the database. This is what you want, right? if enter true validated dated, the data will be added to the database but it will stay on the same page. In this case, make sure you're returning the response from node. There is some problem in your node code then.
the node code is working fine with postman and swagger, the problem is with the function envoyer and valdiate
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.