Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

jake2025's avatar

How to validate date with only year input

Greetings Pros,

I have input box that will only accept year date. Now i want to know how can i validate that the inputted year is a valid year. I'm using Request to validate inputs but i can't validate the inputted year using date and date_format.

I tried this

'pricing_date' => 'required|date_format:Y',
'pricing_date' => 'required|date',

Thanks!

0 likes
8 replies
zachleigh's avatar

What would be a valid year? 1 is a year. So is 20341.

diaglyph's avatar

Perhaps you want to validate a range of years? eg 'min:1900|max:2500|size:4' You need to specify what a "valid" year is for your purpose

1 like
jake2025's avatar

Sorry for incomplete details. I want to validate the year from 1900 to current year.

InaniELHoussain's avatar
Level 32

@jake2025 in the boot method of AppServiceProvider (import carbon)

Validator::extend('date_greater_than', function($attribute, $value, $parameters, $validator) {
            $inserted = Carbon::parse($value)->year;
            $since = $parameters[0];
            return $inserted >= $since && $inserted<= Carbon::now()->year;
});

in your rule

'pricing_date' => 'required|date_greater_than:1900',
4 likes
themsaid's avatar

@jake2025 I'd simply go for this if the input value is a year.

'pricing_date' => 'required|min:1900|max:'.date("Y"),

If the input value is a full date and you only want to validate the year check @InaniELHoussain's answer.

3 likes
eleazarbr's avatar

This worked for me:

'year' => 'required|integer|min:'.date('Y')

alexkudrya's avatar

Rules:

'integer|min:' . (date("Y") - 100) . '|max:' . date("Y") . '|size:4'

Please or to participate in this conversation.