0

i have a input field.

Inside this field the user should only enter text in this format

1+1+2+3

maximum 1+1+1+1+1+1+1+1+1+1+1+1 (12x)

How i can check this only checking for numbers var isnum = /^\d+$/.test($(this).val()); will be the half work, but for more i dont know how...

Code_Ninja
  • 1,729
  • 1
  • 14
  • 38
MikeR
  • 83
  • 8

1 Answers1

4

You can use a quantifier to say how many to accept, so:

var isnum = /^\d+(?:\+\d+){0,11}$/.test($(this).val());

That says to accept any number of digits at the beginning, optionally followed by 0 to 11 examples of + and any number of digits.

Live Example:

function test(str, expect) {
  var result = /^\d+(?:\+\d+){0,11}$/.test(str);
  console.log(str, result, !result === !expect ? "Test:Pass" : "Test:FAIL");
}

test("1", true);
test("1+2+3+4+1234", true);
test("1+1+1+1+1+1+1+1+1+1+1+1", true);
test("1+1+1+1+1+1+1+1+1+1+1+1+1", false);

In a comment you've added:

es only digits and plus-sign and the maximum of entered numbers must be = 12, 6+6 or 3+6+3...

That's a completely different thing, and you can't reasonably test for it with a regular expression (you'd need a ridiculous number of alternatives). Instead, use a regular expression (such as the above) to test the format, then do the sum:

if (/*...the format is good...*/) {
    sum = str.split("+").reduce((a, b) => Number(a) + Number(b));
    if (sum > 12) {
        // disallow it
    }
}

Live Example:

function test(str, expect) {
  var result = /^\d+(?:\+\d+){0,11}$/.test(str);
  if (result) {
    result = str.split("+").reduce((a, b) => Number(a) + Number(b)) <= 12;
  }
  console.log(str, result, !result === !expect ? "Test:Pass" : "Test:FAIL");
}

test("1", true);
test("1+2+3+4+1234", false); // sum > 12
test("1+1+1+1+1+1+1+1+1+1+1+1", true);
test("1+1+1+1+1+1+1+1+1+1+1+1+1", false); // too many
test("12345", false); // sum > 12

In that I've used Number(x) to convert from string to number, but you have a lot of options, which I detail in this answer.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875