user4563161
user4563161

Reputation:

JS regex to only allow increments of 100

What I want to do is only allow increments of 100 in a number with either 3 or 4 digits.

I get how to do it to a certain point, but what I thought would work isn't actually working as I'm getting no matches when testing. I think I now understand why, but I'm a little confused now as what to do to achieve my goal.

So what I want to do is only allow increments of 100 in an input, for instance 3700 would valid but 3723 would not.

What I came up with was this: ^[0-9]{1,2}[0]{2}$. Any help would be much appreciated.

Upvotes: 0

Views: 324

Answers (3)

Stephane Janicaud
Stephane Janicaud

Reputation: 3627

This one should match your need : ^[1-9][0-9]?00$

Here is a sample on regex101

3100 // match
320
3320
100 // match
230
500 // match
5000 // match
1245
000
0000
50002
50000
12000

Upvotes: 1

Marco Bonelli
Marco Bonelli

Reputation: 69367

To make it simple, you need to match (in order):

  1. One non-zero digit [1-9].
  2. Optionally followed by a single digit \d?.
  3. Followed by two zeroes 00 (or 0{2}, as you prefer).

Here you go:

^[1-9]\d?00$

Plus, this is probably not your case since you said you want to match either three or four digits, but if you also want to match 0 (zero):

^(0|[1-9]\d?00)$

Test snippet (zero excluded)

var inp = document.getElementById('inp'),
    res = document.getElementById('res'),
    btn = document.getElementById('btn'),
    exp = /^[1-9]\d?00$/;

function test(e) {
    res.textContent = exp.test(inp.value) ? "Valid." : "Invalid.";
}

btn.addEventListener('click', test);
inp.addEventListener('change', test);
<input id="inp"> <button id="btn">Submit</button>
<p id="res"></p>

Upvotes: 2

Justinas
Justinas

Reputation: 43507

So your number must be #000 or #..#000. So /^([1-9]00|[1-9]\d+00)$/


OR Simply number mod 100 == 0:

var input = prompt('Enter number');

if (input.match(/[^\d]/) || input % 100 != 0) {
  alert('Wrong input.');
} else {
  alert('Correct input');
}

Upvotes: 1

Related Questions