skip to Main Content

I want to make sure that the receiving data is a valid timestamp. is there a way to make sure starts_at and expired_at fields are timestamps?

$rules = [
    'user_id' => 'required|int|exists:users,id',
    'starts_at' => 'required|int|min:1',
    'expires_at' => 'required|int|gt:starts_at',
];

2

Answers


  1. You can define the multi-format date validation in your AppServiceProvider

    class AppServiceProvider extends ServiceProvider  
    {
      public function boot()
      {
        Validator::extend('new-format', function($attribute, $value, $formats) {
    
          foreach($formats as $format) {
    
            $parsed = date_parse_from_format($format, $value);
    
            // validation success
            if ($parsed['error_count'] === 0 && $parsed['warning_count'] === 0) {
              return true;
            }
          }
    
          // validation failed
          return false;
        });
      }
    }
    

    Now you can use the custom validation rule:

    'starts_at' => 'new-format:"Y-m-d H:i:s.u","Y-m-d"'

    Login or Signup to reply.
  2. You can use the date rule when validating timestamp. Then if you want to compare the two dates you can use the before and after rule.

    $rule = [
        'starts_at' => 'date',
        'expired_at' => 'date|after:starts_at',
    ]
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search