[英]How to pass custom props to validate function in redux-form?
我正在尝试创建一个验证函数,如果客户端出现输入错误或服务器返回错误,该函数将返回错误。
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { Form, submit, reduxForm, Field } from 'redux-form';
import Modal from '../../ui/modal';
import { ACCOUNT_REGISTER_MODAL_ID } from './constants';
import registerRequest from './actions';
import CField from '../../ui/form/field';
function validate(values, props) {
const errors = {};
console.log('-');
console.log(values);
console.log(props);
console.log('-');
if (!errors.description && (!values.description || values.description.trim() === '')) {
errors.description = 'Enter a Description';
}
if (!errors.username && (!values.username || values.username.trim() === '')) {
errors.username = 'Enter a Username';
}
return errors;
}
class RegisterModal extends Component {
static propTypes = {
handleSubmit: PropTypes.func,
fields: PropTypes.array,
register: PropTypes.shape({
requesting: PropTypes.bool,
successful: PropTypes.bool,
messages: PropTypes.array,
errors: PropTypes.array,
fieldErrors: PropTypes.array,
}),
dispatch: PropTypes.func,
};
onSubmit = (values) => {
console.log(this.props);
console.log(values);
}
getForm = () => {
this.props.dispatch(submit('register'));
}
render() {
const {
handleSubmit,
fields,
register: {
requesting,
successful,
messages,
errors,
fieldErrors,
},
} = this.props;
console.log(fieldErrors);
const required = value => value ? undefined : 'Required';
return (
<Modal
modalID={ACCOUNT_REGISTER_MODAL_ID}
header={'Connect Account'}
submitText={'Connect'}
onSubmitClick={this.getForm}
register={this.register}
>
<Form
className="ui form register"
onSubmit={handleSubmit(this.onSubmit)}
fieldErrors={fieldErrors}
>
<Field
name="description"
type="text"
component={CField}
label="Please give a recognizable name to this account"
required
placeholder="My main Account"
/>
<Field
name="username"
type="text"
component={CField}
label="Please enter your username"
required
placeholder="foobar2017"
/>
</Form>
</Modal>
);
}
}
const mapStateToProps = state => ({
register: state.RegisterModal,
});
const connected = connect(mapStateToProps, { registerRequest })(RegisterModal);
const formed = reduxForm({
form: 'register',
fields: ['description', 'username'],
validate
})(connected);
export default formed;
传递给 validate 函数的值似乎都没有包含我传递给 Form 组件的“fieldErrors”属性。 我需要能够将 prop 传递到验证函数中,以便我可以访问通过 redux 收到的来自服务器的响应。
是否有不同的方式来创建我的验证功能?
let TicketList = [] // global variable
function () {
TicketList = this.props.tickets;
return (
<Field
validate={validationHandler}
/>
)
}
validationHandler(value){
if(TicketList.includes(value)){
return "error message"
}
}
这对我有用!!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.