【问题标题】:Trying to get validate function to work with redux-form试图让验证功能与 redux-form 一起使用
【发布时间】:2017-06-05 16:05:27
【问题描述】:

我之前在另一个应用程序上试过这个,只是复制代码并编辑了路径,以及我需要为这个应用程序做的事情。我没有收到任何错误,但我似乎无法让它工作。它不会显示任何错误消息或将我的类应用于输入。

import React, { Component } from 'react';
import {Field, reduxForm} from 'redux-form';
import {connect} from 'react-redux';
import * as actions from '../../actions';

class Signin extends Component {
  constructor(props) {
    super(props);

    this.onSubmit = this.onSubmit.bind(this);
  }

  renderField(field) {
    const { meta: {touched, error} } = field;
    const className = `form-group ${touched && error ? 'has-danger' : ''}`;

    return (
      <div className={className}>
        <label><strong>{field.label}:</strong></label>
        <input
          className="form-control"
          type="text"
          {...field.input}
        />
        <div className="text-help">
          { touched ? error : ''}
        </div>
      </div>
    )
  }

  onSubmit({email, password}) {
    console.log(email, password);
  }

  render() {
    const { handleSubmit } = this.props;

    return (
      <form onSubmit={handleSubmit(this.onSubmit)}>
        <Field
          label="Email"
          name="email"
          component={this.renderField}
        />
        <Field
          label="Password"
          name="password"
          component={this.renderField}
        />
        <button type="submit" className="btn btn-success">Sign In</button>
      </form>
    );
  }
}

function validate(values) {
  const errors = {};

  //Validate the inputs from values
  if(!values.email) {
    errors.title = "Enter an email!";
  }
  if(!values.password) {
    errors.categories = "Enter a password!";
  }
  //If errors is empty, the form is fine to submit
  //If errors has any properties, redux form assumes form is invalid
  return errors;
}

export default reduxForm({
  validate,
  form: 'signin'
})(connect(null, actions)(Signin));

【问题讨论】:

  • 当我指的是没有收到任何错误时,这可能有点令人困惑。我的意思是在控制台中没有任何错误或与应用程序的编码端相关。验证中的错误(我想显示的错误)也没有显示。
  • 在验证函数中做一个 console.log(errors) 并检查它是否给出正确的结果
  • 你我的朋友是个天才!我做了控制台日志并意识到它们仍然附加到errors.title和errors.categories。我需要将它们切换到errors.email、errors.password!!

标签: javascript reactjs redux redux-form


【解决方案1】:

所以问题在于附加错误日志的验证功能,因为错误映射到标题和类别,而字段名称是电子邮件和密码

使用

function validate(values) {
  const errors = {};

  //Validate the inputs from values
  if(!values.email) {
    errors.email = "Enter an email!";
  }
  if(!values.password) {
    errors.password = "Enter a password!";
  }
  //If errors is empty, the form is fine to submit
  //If errors has any properties, redux form assumes form is invalid
  return errors;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-04-11
    • 2014-12-17
    • 2018-01-11
    • 1970-01-01
    • 1970-01-01
    • 2019-08-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多