[英]How to centralize forms validations in React?
我想集中表單驗證。 我創建了一個文件: src/schemas/schemas.js 。
在這個文件中,我放置了所有表單驗證,例如:
export const schemaRegister = yup.object().shape({
username: yup.string().required("Username is required").matches(/^[0-9a-z]+$/),
password: yup.string().required("Password is required").min(8).otherValidations...,
passwordConfirmation: yup.string()
.required("Password confirmation is required")
.oneOf([yup.ref("password"), null], "Passwords must match")
});
export const schemaLogin = yup.object().shape({
username: yup.string().required("Username is required"),
password: yup.string().required("Password is required").min(8).otherValidations...,
});
OTHER SCHEMAS
我有兩個疑問:
可以將所有表單驗證模式放在一個文件(src/schemas/schemas.js)中嗎?
如您所見,在這兩種模式中,我都在重復
password: yup.string().required("Password is required").min(8).otherValidations...
有沒有辦法避免重復代碼? 因為我有其他表單,有些字段的驗證比較復雜,所以就不再贅述了
你可以避免重復。 假設您想在schemaRegister
中使用schemaLogin
。 您可以像這樣使用.shape
合並這些模式:
const schemaRegister = schemaLogin.shape({
passwordConfirmation: yup.string()
.required("Password confirmation is required")
.oneOf([yup.ref("password"), null], "Passwords must match")
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.