Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Recursively patten js

I want to check a recursively text that verufy three rules.

1º: All the string should be a sequence of numbers between 0-31 + a dot .

Example: 1.23.5.12

2º: The string can't begin or end with a dot. Like this. .1.23.5.12.

3º You can write a max of 51 digits (following the previous rules)

I tried to make a pattern to my js function. But this dont work.

This is my function:

  var str = document.getElementById("numero").value;
        var patt1 = /^[0-9]+\./g;
        var result = str.match(patt1);
        document.getElementById("demo").innerHTML = result;

What is wrong in the pattern?

like image 525
Abraham Avatar asked Nov 24 '25 11:11

Abraham


1 Answers

You may use

/^(?!(?:\D*\d){52})(?:[12]?\d|3[01])(?:\.(?:[12]?\d|3[01]))*$/

See the regex demo

Details

  • ^ - start of string
  • (?!(?:\D*\d){52}) - fail if there are 52 or more digits separated with any 0+ non-digits
  • (?:[12]?\d|3[01]) - 1 or 2 (optional) followed with any single digit or 3 followed with 0 or 1 (0 - 31)
  • (?:\.(?:[12]?\d|3[01]))* - zero or more consecutive repetitions of
    • \. - dot
    • (?:[12]?\d|3[01]) - see above (0 - 31)
  • $ - end of string.

Use it with test:

if (/^(?!(?:\D*\d){52})(?:[12]?\d|3[01])(?:\.(?:[12]?\d|3[01]))*$/.test(str)) {
    // Valid!
}

Test:

var rx = /^(?!(?:\D*\d){52})(?:[12]?\d|3[01])(?:\.(?:[12]?\d|3[01]))*$/;
var strs = [".12", "123", "1.23.5.12", "12345678"];
for (var s of strs) {
  console.log(s, "=>", rx.test(s));
}
like image 75
Wiktor Stribiżew Avatar answered Nov 27 '25 00:11

Wiktor Stribiżew



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!