好的,我已經結束了一天的作業,而且我的想法不正確。所以這就是我所擁有的...
一個 Laravel 控制器,向它發送一個用戶名,它會告訴我用戶名是否可用,如果不可用,它會給我一個 422 代碼
public function checkUsername(Request $request) {
Validator::make($request->all(), [
'name' => ['required', 'string', 'max:255', 'unique:users'],
])->validate();
return response()->json([
'valid' => true,
'data' => [
'message' => 'Username is available!'
]
], 200);
}
有效回應示例:
{"valid":true,"data":{"message":"Username is available!"}}%
要測驗的卷曲是:
curl -X POST -H "Content-Type: application/json" -d '{"name": "bossryan"}' http://127.0.0.1:8000/api/checkusername
Next: 我有一個使用 Vee-validate 的前端 Vue。它做了很多事情,但我需要將這個最新的驗證添加到組合中,所以如果用戶名被使用(我沒有從上面得到有效的回應,它需要回復“這個用戶名已經被使用”
validateUsername(value) {
// if the field is empty
if (!value) {
return 'This field is required';
}
const regex = /^[a-zA-Z0-9_. -]{4,20}$/i;
if (!regex.test(value)) {
return 'This must be a minimum of 4 characters';
}
return true;
},
這是我創建的 axios,但它不起作用:
const isUnique = (value) => {
return axios.post('/api/checkusername', { email: value }).then((response) => {
// Notice that we return an object containing both a valid property and a data property.
return {
valid: response.data.valid,
data: {
message: response.data.message
}
};
});
};
我知道我需要添加 axios,但我只是有一段時間設定它,我的思緒一直在奔波。我只是在尋找可以幫我插入上面的axios請求的人//一切都很好,所以我可以完成這個。
感謝社區的幫助!
uj5u.com熱心網友回復:
Vee-validate 似乎想要一個已解決的異步驗證承諾。如果狀態 >= 400,Axios 將拒絕該承諾,因此您需要相應地處理它。
假設驗證失敗時回應正文匹配相同的{ valid, data: { message } }格式,您需要類似以下內容
const isUnique = (name) =>
axios.post("/api/checkusername", { name })
.then(({ data }) => data)
.catch(err => ({ // resolve with error details
valid: err.response?.data?.valid ?? false,
data: {
// get the message from the response if it exists
message: err.response?.data?.data?.message ?? "Validation failed"
}
}));
export default {
methods: {
async validateUsername(value) {
// do your synchronous checks as per question
const check = await isUnique(value);
return check.valid || check.data.message;
}
}
}
如果 422 回應正文與預期不符,這將提供一般訊息“驗證失敗” 。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/446168.html
上一篇:Laravel驗證唯一查詢
下一篇:驗證來自api發布請求的欄位
