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
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
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
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.