2015-08-16 92 views
1

在下面的規則,我有我的自定義驗證customRule: *date*Laravel驗證:如何訪問屬性的規則定製驗證

​​

裏面我自定義的驗證規則擴展,我需要訪問規則的date_format屬性:

Validator::extend('customRule', function($attribute, $value, $parameters) { 

    $format = $attribute->getRules()['date_format']; // I need something like this 

    return $format == 'Y-m-d'; 
}); 

如何獲得擴展驗證器上某些屬性的規則值?

回答

1

您不能訪問其他規則。驗證器是獨立的單元 - 應該使用的唯一數據是:字段的

  • 值被驗證傳遞給此驗證規則
  • 值作爲參數對象的其他屬性的
  • 值被驗證

看來,你需要的是一個自定義的驗證,將包是什麼DATE_FORMATcustomRule做:

Validator::extend('custom_date_format', function($attribute, $value, $parameters) { 
    $format = $parameters[0]; 
    $someDate = $parameters[1]; 

    $validator = Validator::make(['value' => $value], ['value' => 'date_format:' . $format]); 

    //validate dateformat 
    if ($validator->fails()) { 
    return false; 
    } 

    //validate custom rule using $format and $someDate and return true if passes 
}); 

一旦你擁有它,你可以用它這樣的:

$rules = [ 
    'my_date' => 'required|custom_date_format:Y-m-d,someDate', 
];