Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Check that a string equals "X.X", where X is a 0-9 digit

I am trying to verify that a string corresponds to this format "x.x" with x, a digit belonging to [0-9].

Right now, what I am doing is:

  • checking that the string is at least, and at most, made of 3 characters
  • checking that the string matches the regex [0-9.] (only digits and a dot)

So right now, I have:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

      myString: Yup.string()
        .min(3, "Minimum 3 caractères: XXX.")
        .max(3, "Maximum 3 caractères: XXX.")
        .matches(/^[0-9]+$/, 'Doit contenir seulement des caractères numériques.')
        .nullable(),

Is there a way for me to:

  • check that myString[0] and myString[2] are digits
  • check that myString[1] is a dot

>Solution :

What about just using the matches and pass a regex that validates the list of requirements in one go?

const number = string().matches(/\d{3,}\.\d{3,}/).nullable();

number.validateSync("123.456") // pass
number.validateSync("12.456") // fail min
number.validateSync("123456") // fail no dot
number.validateSync("1236.4566") // pass

Here \d{3,} matches a number with min 3 digits long followed by a dot \. followed by another \d{3,}.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading