Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Formik, Yup - How to check is Decimal number

Tags:

yup

formik

I have a schema:

const SignupSchema = Yup.object().shape({
  decimal: Yup.number().integer('invalid decimal'),
});

I need to check is number is decimal, but I found only Integer in docs

like image 929
HDallakyan Avatar asked Dec 10 '19 14:12

HDallakyan


People also ask

What is Yup formik validation?

As stated, Formik gives you full freedom to choose any validation method or library to validate various form fields. But as you can see if we use Formik validation then we have to create conditions for each circumstance and field, which can be a huge task if you have a lot of multiple fields, so this where Yup comes to save us.

How do I validate a form in formik?

Manually Triggering Validation You can manually trigger both form-level and field-level validation with Formik using the validateForm and validateField methods respectively. 1 import React from 'react'; 2 import { Formik, Form, Field } from 'formik';

What is formik and how to use it?

Formik is designed to manage forms with complex validation with ease. Formik supports synchronous and asynchronous form-level and field-level validation. Furthermore, it comes with baked-in support for schema-based form-level validation through Yup. We would also use bootstrap so that we won’t waste our time on HTML and CSS.

What happens if I use null in formik?

If you use null, several parts of Formik's computed props (e.g. isValid for example), will not work as expected. How do I test validation? Formik has extensive unit tests for Yup validation so you do not need to test that.


2 Answers

const digitsOnly = (value: string) => /^\d*[\.{1}\d*]\d*$/.test(value) || value.length === 0



const schema = yup.object().shape({
    inputEntry: yup
            .string()
            .test('inputEntry', 'The field should have digits only', digitsOnly)
});

Above code is used for allowing only decimal,whole and null values in the input field.

like image 77
Sairam Gourishetty Avatar answered Oct 07 '22 16:10

Sairam Gourishetty


You can add a custom validation test e.g. with regex.

const SignupSchema = Yup.object().shape({
  decimal: Yup.number().test(
    'is-decimal',
    'invalid decimal',
    value => (value + "").match(/^\d*\.{1}\d*$/),
  ),
});
like image 24
dw_ Avatar answered Oct 07 '22 17:10

dw_