←
🏠 Home yup - How to validate that only numbers are in a string?
Validating numbers is common in frontend apps, however, most validating packages do not come with built-in methods to validate numbers in string. When using yup
, there are not built-in methods for this, even though the problem is so common as mentioned in Issue #927. Luckily, we have yup-numeric
.
Usage
Install yup-numeric
along with it’s peer dependencies.
npm install yup-numeric yup bignumber.js
Create your schema and start validating!
import { numeric } from 'yup-numeric';
const schema = numeric().max('2.0').required('This is required');
const value = '1.0000000000000000000000000000000000001';
const result = await schema.validate(value);
Why not use regex?
The problem with using regex is it is difficult to validate whether if a float is valid in string. On top of that, what if you want a min/max restriction? Unless you want to validate an integer and do not need to validate the value against upper/lower bound.