有什么方法可以使用https://github.com/marmelab/react- admin软件包执行服务器端表单验证?
这是AdminCreate组件的代码。它将创建请求发送到api。如果一切正常,Api将返回状态为422或状态码200的验证错误。
export class AdminCreate extends Component { render() { return <Create {...this.props}> <SimpleForm> <TextInput source="name" type="text" /> <TextInput source="email" type="email"/> <TextInput source="password" type="password"/> <TextInput source="password_confirmation" type="password"/> <TextInput source="phone" type="tel"/> </SimpleForm> </Create>; } }
因此,问题是,如何从服务器发送的错误对象中分别显示每个字段的错误?这是错误对象的示例:
{ errors: {name: "The name is required", email: "The email is required"}, message: "invalid data" }
先感谢您!
class SimpleForm extends Component { handleSubmitWithRedirect = (redirect = this.props.redirect) => this.props.handleSubmit(data => { dataProvider(CREATE, 'admins', { data: { ...data } }).catch(e => { throw new SubmissionError(e.body.errors) }).then(/* Here must be redirection logic i think */); }); render() { const { basePath, children, classes = {}, className, invalid, pristine, record, resource, submitOnEnter, toolbar, version, ...rest } = this.props; return ( <form className={classnames('simple-form', className)} {...sanitizeRestProps(rest)} > <div className={classes.form} key={version}> {Children.map(children, input => ( <FormInput basePath={basePath} input={input} record={record} resource={resource} /> ))} </div> {toolbar && React.cloneElement(toolbar, { handleSubmitWithRedirect: this.handleSubmitWithRedirect, invalid, pristine, submitOnEnter, })} </form> ); } }
现在我有以下代码,它显示验证错误。但是问题是,成功后我无法执行重定向。有什么想法吗?
如果您使用的是SimpleForm,则可以将其asyncValidate与第97期评论中asyncBlurFields所建议的一起使用。我没有使用SimpleForm,所以这就是我能告诉你的。
asyncValidate
asyncBlurFields
我用过一个简单的form。您也可以在其中使用服务器端验证。这是我的方法。一个完整且可行的示例。
form
import React from 'react'; import PropTypes from 'prop-types'; import { Field, propTypes, reduxForm, SubmissionError } from 'redux-form'; import { connect } from 'react-redux'; import compose from 'recompose/compose'; import { CardActions } from 'material-ui/Card'; import Button from 'material-ui/Button'; import TextField from 'material-ui/TextField'; import { CircularProgress } from 'material-ui/Progress'; import { CREATE, translate } from 'ra-core'; import { dataProvider } from '../../providers'; // <-- Make sure to import yours! const renderInput = ({ meta: { touched, error } = {}, input: { ...inputProps }, ...props }) => ( <TextField error={!!(touched && error)} helperText={touched && error} {...inputProps} {...props} fullWidth /> ); /** * Inspired by * - https://redux-form.com/6.4.3/examples/submitvalidation/ * - https://marmelab.com/react-admin/Actions.html#using-a-data-provider-instead-of-fetch */ const submit = data => dataProvider(CREATE, 'things', { data: { ...data } }).catch(e => { const payLoadKeys = Object.keys(data); const errorKey = payLoadKeys.length === 1 ? payLoadKeys[0] : '_error'; // Here I set the error either on the key by the name of the field // if there was just 1 field in the payload. // The `Field` with the same `name` in the `form` wil have // the `helperText` shown. // When multiple fields where present in the payload, the error message is set on the _error key, making the general error visible. const errorObject = { [errorKey]: e.message, }; throw new SubmissionError(errorObject); }); const MyForm = ({ isLoading, handleSubmit, error, translate }) => ( <form onSubmit={handleSubmit(submit)}> <div> <div> <Field name="email" component={renderInput} label="Email" disabled={isLoading} /> </div> </div> <CardActions> <Button variant="raised" type="submit" color="primary" disabled={isLoading} > {isLoading && <CircularProgress size={25} thickness={2} />} Signin </Button> {error && <strong>General error: {translate(error)}</strong>} </CardActions> </form> ); MyForm.propTypes = { ...propTypes, classes: PropTypes.object, redirectTo: PropTypes.string, }; const mapStateToProps = state => ({ isLoading: state.admin.loading > 0 }); const enhance = compose( translate, connect(mapStateToProps), reduxForm({ form: 'aFormName', validate: (values, props) => { const errors = {}; const { translate } = props; if (!values.email) errors.email = translate('ra.validation.required'); return errors; }, }) ); export default enhance(MyForm);
如果代码需要进一步说明,请在下面添加注释,我将尽力加以阐述。
我希望能够通过与调度所描述的onSuccess和onFailure处副作用的动作做的REST请求的动作在这里,但我无法得到这与共同努力SubmissionError。
SubmissionError