praba
praba

Reputation: 105

dd/mm/yyyy format date validation in yii2

I would like to validate date field to accept only (dd/mm/yyyy) format, for example

(14/11/1993)

In addition if the month is February it should not accept day 30 and 31. Please help any one, I've already tried with the pattern below but it's not working in Yii 2. It shows error in RegularExpressionValidator.php

[
    ['dateofbirth'], 
    'match', 
    'pattern' => '/^((([1-2][0-9])|([1-9]))/([2])/[0-9]{4})|((([1-2][0-9])|([1-9])|(3[0-1]))/((1[0-2])|([3-9])|([1]))/[0-9]{4})$/', 
    'message' =>'Invalid date'
],

Upvotes: 0

Views: 3700

Answers (3)

Vladyslav Startsev
Vladyslav Startsev

Reputation: 379

That one worked for me fine

public function rules()
{
    return [
        ['dateofbirth', 'date', 'format' => 'php:Y-m-d'];
    ];
}

Here is more info on that YII2 DateValidator docs

Upvotes: 0

Vishal T
Vishal T

Reputation: 82

try

(/^((0[1-9]|[12][0-9]|3[01])(/)(0[13578]|1[02]))|((0[1-9]|[12][0-9])(/)(02))|((0[1-9]|[12][0-9]|3[0])(/)(0[469]|11))(/)\d{4}$/)

or

(^((0[1-9]|[12][0-9]|3[01])(/)(0[13578]|1[02]))|((0[1-9]|[12][0-9])(/)(02))|((0[1-9]|[12][0-9]|3[0])(/)(0[469]|11))(/)\d{4}$)

Upvotes: 1

SiZE
SiZE

Reputation: 2267

public function rules()
{
    return [
        ['dateofbirth', 'date', 'format' => 'dd/MM/yyyy'],
    ];
}

Another way was taken from this answer.

public function rules()
{
    return [
        ['dateofbirth', 'validateDateOfBirth'],
    ];
}

public function validateDateOfBirth($attribute)
{
    $dateTime = DateTime::createFromFormat('d/m/Y', $this->$attribute);
    $errors = DateTime::getLastErrors();
    if (!empty($errors['warning_count'])) {
        $this->addError($attribute, 'Invalid date');
    }
}

Upvotes: 3

Related Questions