提交失败的表单后显示服务器端验证错误

时间:2017-05-25 22:01:47

标签: validation admin-on-rest react-admin

如何在提交失败的表单后显示验证消息? API请求返回HTTP 400'应用程序/问题+ json'响应,并将违规包含为具有字段路径的列表。

https://tools.ietf.org/html/rfc7807#section-3

{
   "type": "https://example.net/validation-error",
   "title": "Your request parameters didn't validate.",
   "invalid-params": [ 
      {
         "name": "age",
         "reason": "must be a positive integer"
      },
      {
         "name": "color",
         "reason": "must be 'green', 'red' or 'blue'"
      }
   ]
}

1 个答案:

答案 0 :(得分:2)

我有适合您的解决方案, 我建议使用Saga和HttpError做到这一点。

首先,从我们的dataProvider中,我们需要像这样抛出HttpError

...
import {HttpError} from 'react-admin';
...
...

// Make the request with fetch/axios whatever you prefer and catch the error:
// message - the message that will appear in the alert notification popup
// status - the status code
// errors - the errors in key => value format, example in comment below
return fetchClient.request(config).then((response) => {
      return convertHTTPResponse(response, type, resource, params);
    }).catch(function (error) {
      throw new HttpError(error.response.data.message, error.response.status, error.response.data.errors);
    });

然后像这样创建传奇:

import {CRUD_CREATE_FAILURE} from "react-admin";
import {stopSubmit} from 'redux-form';
import {put, takeEvery} from "redux-saga/effects";

export default function* errorSagas() {
  yield takeEvery(CRUD_CREATE_FAILURE, crudCreateFailure);
}

export function* crudCreateFailure(action) {
  var json = action.payload;
  // json structure looks like this:
  // {
  //     username: "This username is already taken",
  //     age: "Your age must be above 18 years old"
  // }
  yield put(stopSubmit('record-form', json));
}

请确保错误(json)的格式与上面的示例相同!

然后将传奇添加到componenet中:

import errorSagas from './sagas/errorSagas';
...
...

<Admin
        customSagas={[ errorSagas ]}
        loginPage={LoginPage}
        authProvider={authProvider}
        dataProvider={dataProvider}
      >

轰!有用 enter image description here

祝你好运!