Yup: How can i validate that only numbers are in a string?

Created on 5 Jun 2020  路  1Comment  路  Source: jquense/yup

Ok, i have this solution:

const digitsOnly = (value) => /^\d+$/.test(value)

Yup
    .string()
    .test('Digits only', 'The field should have digits only', digitsOnly)

But this is so strange, is there really no solution out of the box?

Most helpful comment

string().matches(/^\d+$/) is the builtin method for doing a regex match. There isn't any built-in method for checking if a string is actually a number, but you can add your own

yup.addMethod(yup.string, 'integer', function () {
  return this.matches(/^\d+$/, 'The field should have digits only')
})

>All comments

string().matches(/^\d+$/) is the builtin method for doing a regex match. There isn't any built-in method for checking if a string is actually a number, but you can add your own

yup.addMethod(yup.string, 'integer', function () {
  return this.matches(/^\d+$/, 'The field should have digits only')
})
Was this page helpful?
0 / 5 - 0 ratings