Yup: How to check that a value is a number or change the default error message?

Created on 29 Apr 2016  路  4Comments  路  Source: jquense/yup

Hi,

I have the following schema defined.

const schema = yup.object().shape({
  name: yup.string()
    .required('name is required'),
  age: yup.number()
    .positive('age must be greater than zero')
    .required('age is required')
});

I am also using this with react-formal. When I enter a value for myNumber form field that is not a number, say 'abc', I get the following error message:

this (value: ``) must be a `number` type

I'd like to specify the error message to display when the value is not a number but adding an error message to the number method doesn't seem to work. Is there a way to do this?

Thanks

Most helpful comment

I got it. I needed to call the typeError() function

const schema = yup.object().shape({
  name: yup.string()
    .required('name is required'),
  age: yup.number()
    .typeError('age must be a number')
    .positive('age must be greater than zero')
    .required('age is required')
});

See: https://tonicdev.com/dannief/572294ef4a2c861200c181e5

All 4 comments

I got it. I needed to call the typeError() function

const schema = yup.object().shape({
  name: yup.string()
    .required('name is required'),
  age: yup.number()
    .typeError('age must be a number')
    .positive('age must be greater than zero')
    .required('age is required')
});

See: https://tonicdev.com/dannief/572294ef4a2c861200c181e5

if I type ---- on a <input type="number" />, the .typeError('age must be a number') dont throw an error.

Any ideias?

In case anyone wants to pass a custom error message while using the .oneOf() method, the message must be provided in the second param. For example, let's see how it looks like for a consent checkbox:

{
  consent: Yup.bool().oneOf([true], 'the consent must be accepted'),
}

if I type ---- on a <input type="number" />, the .typeError('age must be a number') dont throw an error.

Any ideias?

I curious about it too :)

Was this page helpful?
0 / 5 - 0 ratings

Related issues

haddyo picture haddyo  路  3Comments

mikkelwf picture mikkelwf  路  4Comments

rigids picture rigids  路  3Comments

ghost picture ghost  路  4Comments

cfteric picture cfteric  路  3Comments