0

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'
],
Bizley
  • 17,392
  • 5
  • 49
  • 59
praba
  • 105
  • 1
  • 3
  • 11

3 Answers3

3
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');
    }
}
Community
  • 1
  • 1
SiZE
  • 2,217
  • 1
  • 13
  • 24
  • yes i already try this type of custom validation,it's validate after posing,at the time the page will refresh so only i need pattern,anyway thank u for your time. – praba Dec 08 '16 at 08:00
1

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}$)

Vishal T
  • 82
  • 6
  • i change your regex like that it's working /^((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}$/ – praba Dec 08 '16 at 08:01
0

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