我正在尝试创建一个验证函数,如果客户端输入错误或服务器返回错误,则会返回错误。
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传递给validate函数,以便我可以通过redux访问从服务器接收的响应。
我应该以不同的方式创建验证功能吗?
答案 0 :(得分:1)
let TicketList = [] // global variable
function () {
TicketList = this.props.tickets;
return (
<Field
validate={validationHandler}
/>
)
}
validationHandler(value){
if(TicketList.includes(value)){
return "error message"
}
}
这对我有用!