反应验证以及清除输入

时间:2018-02-09 15:50:09

标签: javascript jquery validation

我正在尝试找出运行验证的最佳方法。现在,当我提交注册成功但所有验证都会抛出错误,因为我在提交后清除了输入。

一旦表单成功提交,我仍然可以验证和清除输入的最佳方式是什么。

我如何清除function register(user)中的输入,以便在提交时不是空白,或者如果输入了正确的信息,则在表单提交后修复验证不会抛出错误?

import React from 'react';
import { Link } from 'react-router-dom';
import { connect } from 'react-redux';

import { userActions } from '../_actions';

class RegisterPage extends React.Component {
    constructor(props) {
        super(props);

        this.state = {
            user: {
                firstName: '',
                lastName: '',
                username: '',
                password: ''
            },
            submitted: false
        };

        this.handleChange = this.handleChange.bind(this);
        this.handleSubmit = this.handleSubmit.bind(this);
    }

    handleChange(event) {
        const { name, value } = event.target;
        const { user } = this.state;
        this.setState({
            user: {
                ...user,
                [name]: value
            }
        });
    }

    handleSubmit(event) {
        event.preventDefault();

        this.setState({ submitted: true,
       user: {
         firstName: '',
         lastName: '',
         username: '',
         password: ''
       }
     });
        const { user } = this.state;
        const { dispatch } = this.props;
        if (user.firstName && user.lastName && user.username && user.password) {
            dispatch(userActions.register(user));
        }
    }

    render() {
        const { registering  } = this.props;
        const { user, submitted } = this.state;
        return (
            <div className="col-md-6 col-md-offset-3">
                <h2>Register</h2>
                <form name="form" onSubmit={this.handleSubmit}>
                    <div className={'form-group' + (submitted && !user.firstName ? ' has-error' : '')}>
                        <label htmlFor="firstName">Username</label>
                        <input type="text" className="form-control" name="firstName" value={user.firstName} onChange={this.handleChange} />
                        {submitted && !user.firstName &&
                            <div className="help-block">First Name is required</div>
                        }
                    </div>
                    <div className={'form-group' + (submitted && !user.lastName ? ' has-error' : '')}>
                        <label htmlFor="lastName">Password</label>
                        <input type="password" className="form-control" name="lastName" value={user.lastName} onChange={this.handleChange} />
                        {submitted && !user.lastName &&
                            <div className="help-block">Last Name is required</div>
                        }
                    </div>
                    <div className={'form-group' + (submitted && !user.username ? ' has-error' : '')}>
                        <input type="hidden" className="form-control" name="username" value={user.username = user.firstName} onChange={this.handleChange} />
                        {submitted && !user.username &&
                            <div className="help-block">Username is required</div>
                        }
                    </div>
                    <div className={'form-group' + (submitted && !user.password ? ' has-error' : '')}>
                        <input type="hidden" className="form-control" name="password" value={user.password} onChange={this.handleChange} />
                        {submitted && !user.password &&
                            <div className="help-block">Password is required</div>
                        }
                    </div>
                    <div className="form-group">
                        <button className="btn btn-primary">Register</button>
                        {registering &&
                            <img src="data:image/gif;base64,R0lGODlhEAAQAPIAAP///wAAAMLCwkJCQgAAAGJiYoKCgpKSkiH/C05FVFNDQVBFMi4wAwEAAAAh/hpDcmVhdGVkIHdpdGggYWpheGxvYWQuaW5mbwAh+QQJCgAAACwAAAAAEAAQAAADMwi63P4wyklrE2MIOggZnAdOmGYJRbExwroUmcG2LmDEwnHQLVsYOd2mBzkYDAdKa+dIAAAh+QQJCgAAACwAAAAAEAAQAAADNAi63P5OjCEgG4QMu7DmikRxQlFUYDEZIGBMRVsaqHwctXXf7WEYB4Ag1xjihkMZsiUkKhIAIfkECQoAAAAsAAAAABAAEAAAAzYIujIjK8pByJDMlFYvBoVjHA70GU7xSUJhmKtwHPAKzLO9HMaoKwJZ7Rf8AYPDDzKpZBqfvwQAIfkECQoAAAAsAAAAABAAEAAAAzMIumIlK8oyhpHsnFZfhYumCYUhDAQxRIdhHBGqRoKw0R8DYlJd8z0fMDgsGo/IpHI5TAAAIfkECQoAAAAsAAAAABAAEAAAAzIIunInK0rnZBTwGPNMgQwmdsNgXGJUlIWEuR5oWUIpz8pAEAMe6TwfwyYsGo/IpFKSAAAh+QQJCgAAACwAAAAAEAAQAAADMwi6IMKQORfjdOe82p4wGccc4CEuQradylesojEMBgsUc2G7sDX3lQGBMLAJibufbSlKAAAh+QQJCgAAACwAAAAAEAAQAAADMgi63P7wCRHZnFVdmgHu2nFwlWCI3WGc3TSWhUFGxTAUkGCbtgENBMJAEJsxgMLWzpEAACH5BAkKAAAALAAAAAAQABAAAAMyCLrc/jDKSatlQtScKdceCAjDII7HcQ4EMTCpyrCuUBjCYRgHVtqlAiB1YhiCnlsRkAAAOwAAAAAAAAAAAA==" />
                        }
                      {/*  <Link to="/login" className="btn btn-link">Cancel</Link> */}
                    </div>
                </form>
            </div>
        );
    }
}

function mapStateToProps(state) {
    const { registering } = state.registration;
    return {
        registering
    };
}

const connectedRegisterPage = connect(mapStateToProps)(RegisterPage);
export { connectedRegisterPage as RegisterPage };

用户操作

function register(user) {
    return dispatch => {
        dispatch(request(user));

        userService.register(user)
            .then(
                user => {
                    dispatch(success());
                  {/*  history.push('/register'); */}
                    dispatch(alertActions.success('Registration successful'));
                },
                error => {
                    dispatch(failure(error));
                    dispatch(alertActions.error(error));
                }
            );
    };

    function request(user) { return { type: userConstants.REGISTER_REQUEST, user } }
    function success(user) { return { type: userConstants.REGISTER_SUCCESS, user } }
    function failure(error) { return { type: userConstants.REGISTER_FAILURE, error } }
}

非常感谢任何帮助!

2 个答案:

答案 0 :(得分:2)

我认为你应该做的第一件事是从渲染返回中删除所有逻辑。现在基本上你通过有条件地添加has-error类来在div中进行验证。删除它们,而是将验证错误移动到每个字段旁边的状态。像这样:

user: {
         firstName: {
            value: '',
            error: ''
         },
         lastName: '',
         username: '',
         password: ''
       }

此外,您应该有某种验证规则映射,您可以在其中配置哪个字段必须应用哪个规则(如必需,数字等)。在理想情况下,这应该是一个不同的常规服务,可以在您的服务中重复使用下一个表格也。想想它就像你有一个验证服务,你有你的规则集,你有你的国家。然后,您只需将具有规则的状态提供给验证服务,该服务返回一个新状态,其中所有字段都经过验证(错误部分已填充)。额外的状态参数也很好,它告诉你整个状态是否有效。

允许表单提交将基于您的整个有效状态,因此如果状态无效,您可以禁用提交按钮,因此无法调用句柄提交。因此,在提交发生的那一刻,您不必再关心您的验证了。

据我所知,在读出数据之前,你正在清理状态。颠倒逻辑。创建一个单独的函数,重置状态,在表单子上读出数据,重置表单然后调用寄存器。应该没事。

答案 1 :(得分:1)

这是一个简单的简化示例:

class RegisterPage extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      username: {
        value: '',
          error: true
        },
        password: {
          value: '',
          error: true
        }
    };

    this.handleChange = this.handleChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
  }

  handleChange(event) {
    const { name, value } = event.target;
    let error = false;

    if (!value) {
      error = true
    }

    this.setState({
      ...this.state,
      [name]: {
        value,
        error
      }
    });
  }

  handleSubmit(event) {
    event.preventDefault();

    console.log("Dispatching action");
  }

  render() {
    const { registering  } = this.props;
    const { username, password} = this.state;
    return (
        <div>
            <h2>Register</h2>
            <form name="form" onSubmit={this.handleSubmit}>
                    <label>Username</label>
                    <input type="text" name="username" value={username.value} onChange={this.handleChange} />
                    {username.error &&
                        <div>First Name is required</div>
                    }
                    <label>Password</label>
                    <input type="password" name="password" value={password.value} onChange={this.handleChange} />
                    {password.error &&
                        <div>Last Name is required</div>
                    }
                    <button disabled={username.error || password.error}>Register</button>
            </form>
        </div>
    );
  }
}

在这种情况下,我禁用了按钮,因此除非没有错误,否则甚至无法提交。

请记住,这只是一个例子,并没有正确的方法来做到这一点。由您决定实现它的具体程度取决于您。