ReactJS-输入验证不验证

时间:2018-08-30 00:29:59

标签: javascript node.js reactjs validation

我正在尝试验证我的表单。

class Car extends Component {
    constructor() {
        super();
        this.state = {
            name: '',
            errors: {}
        }
     this.handleNameChange = this.handleNameChange.bind(this);
     this.handleSubmit = this.handleSubmit.bind(this);
    }

    componentWillReceiveProps(nextProps) {
        if(nextProps.errors) {
            this.setState({
                errors: nextProps.errors
            });
        }
    }

    handleNameChange(e) {
        this.setState({
            [e.target.name]: e.target.value
        })
    }

    handleSubmit(e) {
        e.preventDefault();
        const car = {
            name: this.state.name,
            ...
        }
        console.log(car);

        axios.post('/api/cars/create', car)
            .then(response => {
                console.log('response.data: ', response.data);

            }).catch(function(err) {
                console.log(err)
            });

    }

    render() {
        const { errors } = this.state;
        console.log('errors name: ', errors.name);
        ...
        return (
            <div className="container" style={{ marginTop: '50px'}}>
                <h2 style={{marginBottom: '40px'}}>Cars</h2>
                <form className="" onSubmit={ this.handleSubmit }>
                    <div className="row">
                        <div className="col-sm-3">
                            <div className="form-group"> 
                                <label>Car Name</label>
                                <input
                                    type="text"
                                    placeholder="Name"
                                    className={classnames('form-control form-control-sm', {
                                        'is-invalid': errors.name
                                    })}
                                    name="name"
                                    onChange={ this.handleNameChange }
                                    value={ this.state.name }
                                />
                                {errors.name && (<div className="invalid-feedback">{errors.name}</div>)}
                            </div>
                        </div>
                        ...
                       );
    }
}
Car = {
    //registerUser: PropTypes.func.isRequired,
    auth: PropTypes.object.isRequired,
    errors: PropTypes.object.isRequired
};

const mapStateToProps = state => ({
    auth: state.auth,
    errors: state.errors
});

export default connect(mapStateToProps,{ registerUser })(withRouter(Car))

然后,在 car.js 中,我有以下内容:

const express = require('express');
const router = express.Router();
const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken');
const passport = require('passport');
const validateCarInput = require('../validation/car');

const Car = require('../models/Car');

router.post('/create', function(req, res) {
    console.log('in /create');
    console.log('req.body.name: '+req.body.name);

    const { errors, isValid } = validateCarInput(req.body);

    if(!isValid) {
        console.log('hello from validation');
        return res.status(400).json(errors);
    }
    ...

如果我发送的表单的字段不正确(空name),我将从控制台hello from validation收到消息。很好。

这是validations/car.js文件:

const Validator = require('validator');
const isEmpty = require('./is-empty');

module.exports = function validateCarInput(data) {
    let errors = {};
    console.log('x data.name: ', data.name);
    data.name = !isEmpty(data.name) ? data.name : '';

    if(Validator.isEmpty(data.name)) {
        errors.name = 'Name field is required';
        console.log('errors.name: ', errors.name);    
    }

    return {
        errors,
        isValid: isEmpty(errors)
    }
}

问题是什么-当我发送带有空name字段的表单时-这意味着该字段无效-它不能为空-NodeJS能够识别这一点,但是对ReactJS组件却不是该信息已通过。

在组件中,此行代码console.log('errors name: ', errors.name);始终为errors.name生成 undefined -然后,该信息将永远不会显示在网站上:

{errors.name && (<div className="invalid-feedback">{errors.name}</div>)}

为什么ReactJS看不到来自NodeJS的消息,而errors.name始终是undefined

2 个答案:

答案 0 :(得分:0)

我认为您应该在请求中添加此.catch((error) => this.setState({error: {names: error}})),但我认为该名称应类似于.catch(function(error) => this.setState({errors: {[name]: error}})),但是您必须知道发生错误的字段的名称是什么< / p>

答案 1 :(得分:0)

根据axio文档,错误响应由可选的response对象构成。响应对象(如果存在)应包含您的服务器端json验证数据,这是您要使用以下命令更新组件状态的内容:

这可能很简单,只需进行以下更改:

axios.post('/api/cars/create', car)
.then(response => {
  console.log('response.data: ', response.data);

})
.catch((error) => { // Use arrow function to simplify setState access 

  // If error contains response data, attempt to extract server
  // side validation to update component state
  if(error.response) {
    this.setState({ errors : error.response.data })
  }
  else {
    console.log(error)
  }
})

有关axio错误处理的更多信息,请参见此https://github.com/axios/axios#handling-errors