提交时或单击时 Redux 表单验证,直到用户键入后才进行验证



我想我可能配置错误或误解。

我有一个包含两个字段的表单,我想对其进行验证。验证只是确保已在字段中输入了某些内容。

我可以在表单pristine时禁用提交按钮,但我真的不喜欢这样做。我宁愿让用户单击提交,然后查看表单中缺少的内容,或者提交表单(如果一切顺利(。

但是,该表单似乎仅在我键入某些内容时才有效。我可以单击两个字段,单击退出,造成模糊,甚至提交表单,它不会向我抛出任何验证。它只会验证我是否键入某些内容然后删除它,它会说它无效。

我的组件...

import React, {Component} from 'react';
import {Field} from "redux-form";
import {renderField, renderTextArea} from './controls';
class AddCommentModal extends Component {
constructor(props) {
super(props);
this.state = {
modalOpen: false
};
this.toggleModal = this.toggleModal.bind(this);
}
toggleModal() {
this.setState({
modalOpen: !this.state.modalOpen
});
this.props.reset();
}

render() {
const {
modalOpen
} = this.state;
const {
submitting, handleSubmit, addMessage
} = this.props;
return (
<div>
<button onClick={this.toggleModal}>Open Modal</button>
<div className={`modal ${modalOpen ? 'is-active' : ''}`}>
<div className="modal-background">{}</div>
<div className="modal-card">
<form onSubmit={handleSubmit(addMessage.bind(this))}>
<header className="modal-card-head">
<p className="modal-card-title">Modal title</p>
<button className="delete" aria-label="close" type="button" onClick={this.toggleModal}>close</button>
</header>
<section className="modal-card-body">
<Field name="name" type="text"
component={renderField} label="Name"
/>
<Field name="message" rows={6}
component={renderTextArea} label="Message"
/>
<div>
</div>
</section>
<footer className="modal-card-foot">
<button className="button is-success" type="submit" disabled={submitting}>Save changes</button>
<button className="button" type="button"  onClick={this.toggleModal}>Cancel</button>
</footer>
</form>
</div>
</div>
</div>
);
}
}
export default AddCommentModal;

我的组件容器

import { connect } from "react-redux";
import AddCommentModal from '../components/AddCommentModal';
import {reduxForm} from "redux-form";
import {addComment} from '../actions/commentActions';
const mapStateToProps = (state, ownProps) => {
return {
};
};
const mapDispatchToProps = (dispatch, ownProps) => {
return {
addMessage: dispatchAddMessage.bind(this)
};
};
const validate = values => {
let errors = {};
if(!values.name || values.name.trim() === '') errors.name = 'Please Provide Your Name';
if(!values.message || values.message.trim() === '') errors.message = 'Please Provide A Message';
return errors;
};
const dispatchAddMessage = (values, dispatch, ctx) => {
return dispatch(addComment(values.name, values.message));
};
const AddCommentModalForm = reduxForm({
form: 'AddCommentModalForm',
validate,
})(AddCommentModal);
export default connect(mapStateToProps, mapDispatchToProps)(AddCommentModalForm);

我最初进行了字段级验证,因为验证非常简单,但这不起作用,因此尝试了同步验证,但这仍然不起作用。有什么想法吗?

我不确定您是否仍在寻找这个问题的答案,但似乎存在与验证和使用reset()方法相关的问题。请参阅此处的 GitHub 上的未解决问题:

https://github.com/redux-form/redux-form/issues/2971

线程中包含一些解决方法和更多详细信息。由于您在代码中使用了reset方法,因此它可能适用于您的问题。

最新更新