I'm trying to add form validations using yup
to a React form component using formik
. My validation seems to work, but I find it too verbose.
Trying to use the .addMethod()
function of yup
, but getting stuck on the syntax or maybe this is overkill?
Summary: I would like to convert my validation into an actual method using yup.addMethod()
.
Actual validation:
import * as yup from 'yup'
const countryNameRegex = /[A-Za-z]/g;
const countryCodeRegex = /[a-zA-Z]{2,}/g;
const isRequired = 'Required Field'
const isCorrectFormat = 'The country name may contain only letters'
const countryValidationSchema = yup.object().shape({
name: yup.string()
.min(3, `country name must contain at least 3 characters`)
.matches(
countryNameRegex,
{
message: isCorrectFormat,
excludeEmptyStrings: true
}
)
.label(`Country Name`)
.required(isRequired),
code: yup.string()
.length(2, `The country code must be exactly 2 letters`)
.matches(
countryCodeRegex,
{
message: isCorrectFormat,
excludeEmptyStrings: true
}
)
.label('Country Code')
.required(isRequired),
});
export default countryValidationSchema;
My tryout using the yup.addMethod()
function isValidCountryName(ref, msg) {
return yup.mixed().test({
name: 'isValidCountry',
exclusive: false,
message: msg || `${ref.path} must be a valid country name`,
params: {
reference: ref.path,
},
test(value) {
const isRightFormat = this.resolve(ref);
return isRightFormat; [//ASK] should be doing the checks or transformations here
},
});
}
yup.addMethod(yup.string, 'isValidCountryName', isValidCountryName)