Compare 2 dates from input in validation Part 2

I found a better way to implement this by modifying validate_after and validate_before to check if the given value(the one used to compare against) exists as an input.

Use the same code from this tutorial except we don’t need the custom message(don’t forget the method that builds it),  we use the native  validate_after and validate_before and the extended Validator will contain:

 


<?php

class Validator extends Laravel\Validator
{

    /**
     * Validate the date is before a given date.
     *
     * @param  string  $attribute
     * @param  mixed   $value
     * @param  array   $parameters
     * @return bool
     */
    protected function validate_before($attribute, $value, $parameters)
    {

        /*
         * If a input with the name equal to the value we compare with, we
         * use it, otherwise we proceed as usual
         */

        if( isset( $this->attributes[ $parameters[0] ] ) )
        {

          $value_to_compare = $this->attributes[ $parameters[0] ];

        }//if we have an input with this name
        else
        {

            $value_to_compare = $parameters[0];

        }//we compare with the provided value

        return ( strtotime( $value ) < strtotime( $value_to_compare ) );

    }//validate_before

    /**
     * Validate the date is after a given date.
     *
     * @param  string  $attribute
     * @param  mixed   $value
     * @param  array   $parameters
     * @return bool
     */
    protected function validate_after($attribute, $value, $parameters)
    {
        /*
         * If a input with the name equal to the value we compare with, we
         * use it, otherwise we proceed as usual
         */

        if( isset( $this->attributes[ $parameters[0] ] ) )
        {

            $value_to_compare = $this->attributes[ $parameters[0] ];

        }//if we have an input with this name
        else
        {

            $value_to_compare = $parameters[0];

        }//we compare with the provided value

        return ( strtotime( $value ) > strtotime( $value_to_compare ) );

    }//validate_after

}//end class

Advertisements

One thought on “Compare 2 dates from input in validation Part 2

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s