user1931780
user1931780

Reputation: 466

javascript regex validate years in range

I have input field for year and I need a regex for validation it. I have such code: ^([12]\d)?(\d\d)$. But I want allow to validate only years in certain range (1990-2010, for example). How can I do it?

Edit. range must be 1950-2050

Upvotes: 14

Views: 37700

Answers (8)

Valentin Stanchev
Valentin Stanchev

Reputation: 1

Here is a regex if you want to find a year in a film name for example. Years b/n 1900 - 2029 and some symbols are allowed wrapping the year .-_+[(

(?<=(?:\s|\.|_|\-|\+|\(|\[))(?:19[2-9]|20[0-2])\d(?=\s|$|\.|_|\-|\+|\)|\])

check it out here https://regex101.com/r/eQ9zK7/82

Note you can not start with year, because there is at least interval in front. In the example first few lines are matching, because we have multiple lines in a single line they wont match.

1917.2019.1080p... even if 1917 was in range it will mark only 2019

Upvotes: 0

Alireza tk
Alireza tk

Reputation: 475

if you want to check for age between for example 18 or 70 I did it like this. my solution was

function yearRange(year) {
  let now = new Date().getFullYear();
  let age = now - Number(year);
  if (age < 18 || age > 70) return false;
  return true;
}

Upvotes: 1

S.Elavarasan
S.Elavarasan

Reputation: 83

Regex for Current Year(Dynamic) from 1995

var current_year = new Date().getFullYear().toString().split("");
var reg=new RegExp("^(199[5-9]|200[0-9]|[0-"+current_year[0]+"][0-"+current_year[1]+"][0-"+current_year[2]+"][0-"+current_year[3]+"])$");
reg.test("1995");

Upvotes: 2

mishik
mishik

Reputation: 10003

Try this:

1990 - 2010:

/^(199\d|200\d|2010)$/

1950 - 2050:

/^(19[5-9]\d|20[0-4]\d|2050)$/

Other examples:

1945 - 2013:

/^(194[5-9]|19[5-9]\d|200\d|201[0-3])$/

1812 - 3048:

/^(181[2-9]|18[2-9]\d|19\d\d|2\d{3}|30[0-3]\d|304[0-8])$/

Basically, you need to split your range into easy "regexable" chunks:

1812-3048: 1812-1819 + 1820-1899 + 1900-1999 + 2000-2999 + 3000-3039 + 3040-3048
    regex: 181[2-9]    18[2-9]\d   19\d\d      2\d{3}      30[0-3]\d   304[0-8]

Upvotes: 39

Andr&#233; Dion
Andr&#233; Dion

Reputation: 21728

Regex:

/^(19[5-9]\d|20[0-4]\d|2050)$/

Easier...

var year = parseInt(textField.value, 10);
if( year >= 1950 && year <= 2050 ) {
    ...
}

Upvotes: 4

HamZa
HamZa

Reputation: 14931

For a range from 1950 to 2050 you may use the following regex:

^19[5-9]\d|20[0-4]\d|2050$

Online demo

Upvotes: 7

HBP
HBP

Reputation: 16043

RegExp does not seem to be the right tool here. If you have the year values already isolated surely a simple comparison would work :

if (+yr >= 1990 && +yr <= 2010)

The +yr converts the string to a number

Upvotes: 11

Pieter
Pieter

Reputation: 1833

(199[0-9]|200[0-9]|2010)

This will work in your 'example case'.

Helpful website: http://utilitymill.com/utility/Regex_For_Range

Upvotes: 2

Related Questions