I have a validation schema defined using Yup as below
export const mySchema = {
['add-record']: yup.object().shape({
'myId': yup
.string()
.nullable()
.required()
})
}
On click of some button, I invoke the validation as below;
await mySchema['add-record'].validate(props.formRef.current.getValues("myId"), { context: { other: 4 } });
props.formRef.current.getValues("myId") is actually mapped to a textbox on the UI and as soon as I enter 123456789 and invoke the validation, I get an error saying;
this must be a object
type, but the final value was: null
(cast from the value "123456789"
).
Not sure why it is saying the final value is: null
UPDATED
I have a server API call in my main component and based on that API response, I want to display the server error message via Yup’s context.createError…So I want to pass isMyIdServiceError and MyIdServiceErrorMsg and display the error message in MyIdServiceErrorMsg, if isMyIdServiceError is true
I am trying the below, but it does not work. Please suggest.
'myId': yup
.string()
.nullable()
.required()
.when(
['$isMyIdServiceError', '$MyIdServiceErrorMsg'],
([isMyIdServiceError, MyIdServiceErrorMsg], schema) => {
if (isMyIdServiceError === true) {
context.createError({
message: MyIdServiceErrorMsg
});
}
}
),
Trying with test also throws ValidatonError in the console
'myId': yup
.string()
.nullable()
.required()
.test(
'api-error',
'${$MyIdServiceErrorMsg}',
async function(value, ctx) {
const {
ismyIdServiceError,
myIdServiceErrorMsg
} = this.options.context;
if (ismyIdServiceError) {
return ctx.createError({ path: 'myId', message: myIdServiceErrorMsg });
}
return true;
}
)
2
Answers
The error you’re seeing is because mySchema[‘add-record’] is expecting an object, but you’re passing a string value directly.
In your schema definition, you’ve defined mySchema[‘add-record’] as an object with a property of ‘myId’, so when you call validate, it expects you to pass in an object with the same structure.
You should use the getValues() method without argument to get the entire form values as an object, then validate that object with your schema.
try this :
try this for the error :
Then, when calling validate(), you’ll need to pass in the context like this: