我想我可能有错误配置或可能是误解。
我有一个包含两个字段的表单,我希望对其进行验证。验证只是确保在现场输入了一些东西。
我可以在表单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);
我最初进行了字段级验证,因为验证非常简单,但是没有用,所以尝试同步验证但仍然无效。有任何想法吗?
答案 0 :(得分:0)
我不确定您是否仍在寻找该问题的答案,但是似乎存在一个与验证和reset()
方法的使用有关的问题。请在此处参考GitHub上的未解决问题:
https://github.com/redux-form/redux-form/issues/2971
该线程中包含一些变通办法和更多详细信息。由于您在代码中使用了reset
方法,因此它可能适用于您的问题。