Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

      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
like image 333
Cucumberbatch Avatar asked Feb 03 '26 21:02

Cucumberbatch


2 Answers

Another way is to use /^[0-9][.][0-9]$/, which I think is easier to read. Here is an example with tests:

const regex= /^[0-9][.][0-9]$/;

console.log(regex.test("4.3")); // true
console.log(regex.test("9.0")); // true

console.log(regex.test("91.0")); // false
console.log(regex.test("4e3")); // false
console.log(regex.test("abc")); // false

With Yup, in your case, it would be:

Yup.string()
  .matches(
    /^[0-9][.][0-9]$/,
    'It should be in the form of Digit + Period + Digit'
  )
  .nullable();

Also, you can copy past the RegEx in regexr.com to get an explanation of each part of it.

like image 193
yousoumar Avatar answered Feb 05 '26 10:02

yousoumar


You can improve your code just using regex, like in your case:

yup.string()
  .matches('^\d{1}\.\d{1}$', 'Doit contenir seulement des caractères numériques.')
  .nullable()

\d validates whether first and last characters are digits with second character being a .

Since you only need one number its d{1} before and after the dot.

Edit:

As @bobble bubble mentioned and after testing d{1} is actually redundant. In your case, the regex pattern is ^\d\.\d$. You can use the above pattern if you want to increase the digit count.

like image 21
Lakshitha Wisumperuma Avatar answered Feb 05 '26 10:02

Lakshitha Wisumperuma