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

Regex to allow only in range 1-45 with single hyphen

i tried to create a Regex to allow only in input in a range from below format with single hyphen.

Match

1-45
2-10
12-45

Not Match

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

1-
-2
1-45-
1,45
145

but most of the regex allow multiple hyphen

>Solution :

Assuming you are using JavaScript, I prefer a splitting approach here:

var input = "12-45";
var pass = false;
if (/^\d+-\d+$/.test(input)) {
    var nums = input.split("-");
    if (nums[0] >= 1 && nums[0] <= 45 && nums[1] >= 1 && nums[1] <= 45) {
        pass = true;
    }
}

if (pass) {
    console.log("VALID");
}
else {
    console.log("INVALID");
}
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