Jump to content

Over 18 regex


giraffemedia

Recommended Posts

Hello, I'm trying to put together a regex that validates a two number input. I want a person to enter their age but it has to be 18 or over and up to 99.

 

I've tried using ^([1-9][8-9])$ but obviously that only validates 18, 19, 28, 29, 38, 39 etc missing out the other numbers.

 

Can anyone help please?

Link to comment
https://forums.phpfreaks.com/topic/250755-over-18-regex/
Share on other sites

Why would you use regex for this?

Surely it's easier to just use regular php

 

$age = (int) $_POST['age'];
if($age >= 18 && $age <= 99) {
    // Age is correct
} else {
    // Age is incorrect
}

Hi Jay, if you read my 2nd post you'll see I can only enter a regex for validation.

Link to comment
https://forums.phpfreaks.com/topic/250755-over-18-regex/#findComment-1286526
Share on other sites

JAY6390's example will only be true for values less than 100.

 

^(?:[1-9]\d{2,}+|[2-9]\d|1[89])$

 

The first section checks for 1-9 followed by 2 or more digits. This covers all numbers greater than 99

The second checks for a number between 2-9 followed by a single number. This covers all two digit numbers over 19

The final checks for a 1 followed by either an 8 or a 9. This covers 18 and 19.

 

The RegEx doesn't allow leading 0's, but this could be checked fairly easily by adding something like 0*+ immediately after the opening ^.

 

Hope this helps.

 

Link to comment
https://forums.phpfreaks.com/topic/250755-over-18-regex/#findComment-1286698
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.