gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 15:18:56 25 4
gpt4 key购买 nike

表单提交失败后如何显示验证消息? API 请求返回 HTTP 400 'application/problem+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'"
}
]
}

最佳答案

我有你的解决方案
我建议用 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) 的格式与上例相同!

然后在组件中插入 saga:
import errorSagas from './sagas/errorSagas';
...
...

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

繁荣!有用
enter image description here

祝你好运!

关于validation - 表单提交失败后显示服务器端验证错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44190490/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com