Yup: How apply regexp for validate number? How to change message for required?

Created on 10 May 2018  路  6Comments  路  Source: jquense/yup

I'm trying to validate a number field.

    Yup.object().shape({
        temperature: Yup.number()
                        .min(0, 'Minimal value 0')
                        .max(30, 'Maximum value 30') 
                        .matches(/^([0]([.][0-9]+)?|[1-9]([0-9]+)?([.][0-9]+)?)$/, {
                            message:'Inccorect format. Example 25 or 25.1',
                            excludeEmptyString: true
                        })
                        .required('Temperature is required. Please enter value from 0 till 30')
    })

I got error if apply matches for number,

and I can not to change message for required. I got default message.

  1. How apply regexp for validate number?
  2. How to change message for required?

Most helpful comment

@zhrvdns Would you mind showing how you accomplished this? And thanks @jquense for this awesome validation tool.

Thanks!

All 6 comments

There isn't currently a way to validate a number against a regex since it's not a string. You'd have to convert it to a string, validate it, and convert it back, but you are _may_ lose data in the conversion so it's not particularly safe to do.

That is the right way to change the message for required i'm not sure why it wouldn't work, can you post a repo in codesandbox?

Thanks for the explanation! I will use Yup.string() for matches and required. Check for min and max I'll write on my own.

Issue can be closed.

@zhrvdns Would you mind showing how you accomplished this? And thanks @jquense for this awesome validation tool.

Thanks!

@zhrvdns I would also like to see how it works

Thanks

do you have any sample code?

Thanks for the explanation! I will use Yup.string() for matches and required. Check for min and max I'll write on my own.

Issue can be closed.

do have sample code how did you achieved this?

This is how I tested for number and for regex; I used mixed and wrote custom tests.

const schema = yup.object().shape({
  price: yup
    .mixed()
    .required('Price is required')
    .test('type', "Price must be a number", value => !isNaN(value))
    .test('validDollar', "Price must be a valid dollar amount", value => /^\d*.?\d{0,2}$/.test(value)),

Was this page helpful?
0 / 5 - 0 ratings