简体   繁体   English

表单验证问题 react js node js

[英]Problem with form validation react js node js

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 !所以我刚刚用节点 js 准备了一个表单并响应 js,当我尝试使用 Postman 添加用户时,它与验证和所有内容完美配合,但随后我尝试将其链接到我的字体端,但它没有工作,问题是如果我输入一个真实的数据,它会被添加到我的数据库中并移动到下一页,当我输入错误的数据时,它不会添加到我的后端,但它仍然会移动到下一页!

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反应 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 !请帮我 !

Return the error from your validate method.从您的验证方法返回错误。

Working example here => https://stackblitz.com/edit/react-zfwvuh?file=src%2FApp.js这里的工作示例 => 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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM