表单验证问题 react js node js
2020-09-18
374
所以我刚刚用 node js 和 react 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
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
请帮帮我!
1个回答
从验证方法返回错误。
此处的工作示例 => 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;
Prateek Thapa
2020-09-18