Code snippets for symfony 1.x

Navigation

Refine Tags

Snippets tagged "validator longitude"

Validator for latitude / longitude

<?php
/**
 * This validator accepts either a four-member array such as
 * array( 'deg' => 12, 'min' => 34, 'sec' => 56, 'dir' => 'N' )
 * or a numeric value such as 12.3456
 */
class ynValidatorLatLong extends sfValidatorBase
{
  protected function configure($options = array(), $messages = array())
  {
    parent::configure( $options, $messages );
 
    $this->addRequiredOption('axis');  // 'latitude' || 'longitude'
 
    $this->addMessage('invalid_axis', 'The selected axis is invalid.');
  }
 
  protected function doClean( $value )
  {
    $max = 0;
 
    switch ( $this->getOption('axis') ) {
      case 'latitude':
        $max = 90;
        break;
 
      case 'longitude':
        $max = 180;
        break;
 
      default:
        throw new sfValidatorError($this, 'invalid_axis');
    }
 
    if ( is_array( $value ) ) {
      $value = $this->arrayToInt( $value );
    }
 
    if ( ! is_numeric( $value ) ) {
      throw new sfValidatorError($this, 'invalid');
    }
 
    if ( abs( $value ) > $max ) {
      throw new sfValidatorError($this, 'invalid');
    }
 
    return $value;
  }
 
  protected function arrayToInt( array $value )
  {
    if ( count( $value ) != 4 ) {
      throw new sfValidatorError($this, 'invalid');
    }
 
    if (
      ! isset( $value['deg'] )
      || ! isset( $value['min'] )
      || ! isset( $value['sec'] )
      || ! isset( $value['dir'] )
    ) {
      throw new sfValidatorError($this, 'invalid');
    }
 
    if ( preg_match( '/\D/', $value['deg'].$value['min'].$value['sec'] ) ) {
      // non-integer component
      throw new sfValidatorError($this, 'invalid');
    }
 
    $multiplier = 1;
 
    switch ( strtolower( $value['dir'] ) ) {
      case 'n':
        $axis = 'latitude';
        break;
 
      case 's':
        $axis = 'latitude';
        $multiplier = -1;
        break;
 
      case 'e':
        $axis = 'longitude';
        break;
 
      case 'w':
        $axis = 'longitude';
        $multiplier = -1;
        break;
 
      default:
        throw new sfValidatorError($this, 'invalid');
    }
 
    if ( $axis != $this->getOption('axis') ) {
      throw new sfValidatorError($this, 'invalid');
    }
 
    return ( $value['deg'] + $value['min']/60 + $value['sec']/60/60 ) * $multiplier;
  }
}
 
/*
 * UNIT TEST
 */
 
<?php
require_once dirname(__FILE__).'/../../bootstrap/unit.php';
 
$t = new lime_test();
 
$lat_validator = new ynValidatorLatLong( array( 'axis' => 'latitude' ) );
$lon_validator = new ynValidatorLatLong( array( 'axis' => 'longitude' ) );
 
$lat_good = array(
  array( 'deg' => 50, 'min' => 12, 'sec' => 14, 'dir' => 'N' ),
  array( 'deg' => 50, 'min' => 12, 'sec' => 14, 'dir' => 'S' ),
  50.456789,
  50,
  -50.456789,
  -50
);
 
$lat_bad = array(
  'three members' => array( 'deg' => 50, 'min' => 12, 'sec' => 14 ),
  'invalid n/s 1' => array( 'deg' => 50, 'min' => 12, 'sec' => 14, 'dir' => 'F' ),
  'invalid n/s 2' => array( 'deg' => 50, 'min' => 12, 'sec' => 14, 'dir' => 'E' ),
  'non-integer member' => array( 'deg' => 50, 'min' => 12, 'sec' => 14.2, 'dir' => 'N' ),
  'out of range' => array( 'deg' => 100, 'min' => 12, 'sec' => 14, 'dir' => 'N' ),
);
 
$lon_good = array(
  array( 'deg' => 150, 'min' => 12, 'sec' => 14, 'dir' => 'E' ),
  array( 'deg' => 150, 'min' => 12, 'sec' => 14, 'dir' => 'W' ),
  50.456789,
  50,
  -50.456789,
  -50
);
 
$lon_bad = array(
  'three members' => array( 'deg' => 150, 'min' => 12, 'sec' => 14 ),
  'invalid e/w 1' => array( 'deg' => 150, 'min' => 12, 'sec' => 14, 'dir' => 'F' ),
  'invalid e/w 2' => array( 'deg' => 150, 'min' => 12, 'sec' => 14, 'dir' => 'N' ),
  'non-integer member' => array( 'deg' => 150, 'min' => 12, 'sec' => 14.2, 'dir' => 'E' ),
  'out of range' => array( 'deg' => 200, 'min' => 12, 'sec' => 14, 'dir' => 'E' ),
);
 
foreach ( $lat_good as $value ) {
  try {
    $clean = $lat_validator->clean( $value );
    $t->ok( is_numeric( $clean ), 'is numeric' );
 
    if ( is_array( $value ) ) {
      switch( $value['dir'] ) {
        case 'E':
          $multiplier = 1;
          break;
        case 'W':
          $multiplier = -1;
          break;
      }
 
      $t->ok( abs($clean) >= $value['deg'] && abs($clean) <= $value['deg']+1, "value $clean makes sense" );
      $t->ok( $clean * $multipler >= 0, 'direction correct' );
    }
    else {
      $t->is( $value, $clean, 'value makes sense' );
    }
  }
  catch( sfValidatorError $e ) {
    $t->fail( $e->getMessage() );
  }
}
 
foreach ( $lat_bad as $message => $value ) {
  try {
    $lat_validator->clean( $value );
    $t->fail( $message );
  }
  catch( sfValidatorError $e ) {
    $t->pass( $message );
  }
}
 
foreach ( $lon_good as $value ) {
  try {
    $clean = $lon_validator->clean( $value );
    $t->ok( is_numeric( $clean ), 'is numeric' );
 
    if ( is_array( $value ) ) {
      switch( $value['dir'] ) {
        case 'E':
          $multiplier = 1;
          break;
        case 'W':
          $multiplier = -1;
          break;
      }
 
      $t->ok( abs($clean) >= $value['deg'] && abs($clean) <= $value['deg']+1, "value $clean makes sense" );
      $t->ok( $clean * $multipler >= 0, 'direction correct' );
    }
    else {
      $t->is( $value, $clean, 'value makes sense' );
    }
  }
  catch( sfValidatorError $e ) {
    $t->fail( $e->getMessage() );
  }
}
 
foreach ( $lon_bad as $message => $value ) {
  try {
    $lon_validator->clean( $value );
    $t->fail( $message );
  }
  catch( sfValidatorError $e ) {
    $t->pass( $message );
  }
}
 
by yitznewton on 2011-02-27, tagged coordinates  form  latitude  longitude  validator 

Latitude Longitude Validator

A Latitude Longitude validator that allows you to specify very exact constraints for the co-ordinates that are submitted.

<?php
 
/*
 * This file is part of the symfony package.
 * (c) 2004-2006 Fabien Potencier <fabien.potencier@symfony-project.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
 
/**
 * myLatLngValidator 
 * 
 * @description This class validator will validate the entered latitude and
 * longitudes submitted using a form or other method.
 * @subpackage validator
 * @author Nathan Rzepecki
 * @created 21/4/2008
 */
class myLatLngValidator extends sfValidator
{
  /**
   * Executes this validator.
   * 
   * @param mixed A file or parameter value/array
   * @param error An error message reference
   *
   * @return bool true, if this validator executes successfully, otherwise false
   */
  public function execute(&$value, &$error)
  {
//
//      echo '<pre>value is: '.$value.'</pre>';
//      echo '<pre>min_type: '.$this->getParameterHolder()->get('min_type').'</pre>';
//      echo '<pre>max type: '.$this->getParameterHolder()->get('max_type').'</pre>';
//      echo '<pre>min: '.$this->getParameterHolder()->get('min').'</pre>';
//      echo '<pre>max: '.$this->getParameterHolder()->get('max').'</pre>';
//      exit;
 
//      echo '<pre>value: '.$value.'</pre>';
//      echo '<pre>max type: '.$this->getParameterHolder()->get('max_type').'</pre>';
//      echo '<pre>min type: '.$this->getParameterHolder()->get('min_type').'</pre>';
//      echo '<pre>min: '.$this->getParameterHolder()->get('min').'</pre>';
//      echo '<pre>max: '.$this->getParameterHolder()->get('max').'</pre>';
//      echo '<pre>'..'</pre>';
 
    /*
     * If the min_type was set
     */
      if ($this->getParameterHolder()->get('min_type') == '+')
      {
         // type was positive
         $re = '/^\d{1,3}(\.(\d*)){0,1}$/';
         if (!preg_match($re, $value))
         {
           $error = $this->getParameterHolder()->get('min_type_error');
           return false;
         } // end if
      }
      elseif ($this->getParameterHolder()->get('min_type') == '-')
      {
        // type was negative
        $re = '/^-\d{1,3}(\.(\d*)){0,1}$/';
         if (!preg_match($re, $value))
         {
           $error = $this->getParameterHolder()->get('min_type_error');
           return false;
         } // end if
      }
      else
      {
        // don't care if it is plus or minus
         $re = '/^-{0,1}\d{1,3}(\.(\d*)){0,1}$/';
         if (!preg_match($re, $value))
         {
           $error = $this->getParameterHolder()->get('min_type_error');
           return false;
         } // end if
      } // end if elseif else
 
 
    /*
     * if max_type was set
     */            
      if ($this->getParameterHolder()->get('max_type') == '+')
      {
         // type was positive
         $re = '/^\d{1,3}(\.(\d*)){0,1}$/';
         if (!preg_match($re, $value))
         {
           $error = $this->getParameterHolder()->get('max_type_error');
           return false;
         } // end if
      }
      elseif ($this->getParameterHolder()->get('max_type') == '-')
      {
        // type was negative
        $re = '/^-\d{1,3}\.{0,1}\d+$/';  // negative digit
         if (!preg_match($re, $value))
         {
           $error = $this->getParameterHolder()->get('max_type_error');
           return false;
         } // end if
      }
      else
      {
        // don't care if it is plus or minus
         $re = '/^-{0,1}\d{1,3}(\.(\d*)){0,1}$/';
         if (!preg_match($re, $value))
         {
           $error = $this->getParameterHolder()->get('max_type_error');
           return false;
         } // end if
      } // end if elseif else
 
 
    /*
     * if max value was set
     */
     if ($this->getParameterHolder()->get('max'))
     {
       $re = '/^-\d{1,3}(\.(\d*)){0,1}$/';  // negative digit
       if (preg_match($re, $this->getParameterHolder()->get('max')))
       {
          // yes its a negative so remove the prefix -
          $maxValue = substr($this->getParameterHolder()->get('max'), 1);
 
          if (!preg_match($re, $value))
          {
            $error = $this->getParameterHolder()->get('max_type_error');
            return false;
          }
          else
          {
            // both the max value and the value are negative so test that the value is less than the max value
            if (!($maxValue > substr($value, 1)))
            {
              $error = $this->getParameterHolder()->get('max_error');
              return false;
            } // end if 
          } // end if else          
       } 
       else
       {
         $maxValue = $this->getParameterHolder()->get('max');
 
         $re = '/^\d{1,3}(\.(\d*)){0,1}$/';  // positive digit
         if (preg_match($re, $value))
         {
           // Yeah the value is a positive so make sure its within range
           if (!($maxValue > $value))
           {
              $error = $this->getParameterHolder()->get('max_error');
              return false;
           } // end uf
         }
         else
         {
           $error = $this->getParameterHolder()->get('max_type_error');
           return false;
         } // end if else positive
 
       }// end if
 
     } // end if
 
 
    /*
     * if min value was set
     */
     if ($this->getParameterHolder()->get('min'))
     {
       $re = '/^-\d{1,3}(\.(\d*)){0,1}$/';  // negative digit
       if (preg_match($re, $this->getParameterHolder()->get('min')))
       {
          // yes its a negative so remove the prefix -
          $minValue = substr($this->getParameterHolder()->get('min'), 1);
 
          if (!preg_match($re, $value))
          {
            // the min value was negative so the value should be nexative. This is not so error it
            $error = $this->getParameterHolder()->get('min_type_error');
            return false;
          }
          else
          {
            // both the max value and the value are negative so test that the value is less than the max value
            if (!(substr($value, 1) > $minValue))
            {
              $error = $this->getParameterHolder()->get('min_error');
              return false;
            } // end if 
          } // end if else          
       } 
       else
       {
         $minValue = $this->getParameterHolder()->get('min');
 
         $re = '/^\d{1,3}(\.(\d*)){0,1}$/';  // positive digit
         if (preg_match($re, $value))
         {
           // Yeah the value is a positive so make sure its within range
           if (!($value > $minValue))
           {
              $error = $this->getParameterHolder()->get('min_error');
              return false;
           } // end if
         }
         else
         {
           $error = $this->getParameterHolder()->get('min_type_error');
           return false;
         } // end if else positive
 
       }// end if
 
     } // end if
 
    // was not returned out of any of the above so must be good
    return true;
  }
 
  /**
   * Initializes this validator.
   *
   * @param sfContext The current application context
   * @param array   An associative array of initialization parameters
   *
   * @return bool true, if initialization completes successfully, otherwise false
   */
  public function initialize($context, $parameters = null)
  {
    // initialize parent
    parent::initialize($context, $parameters);
 
    // set defaults
    $this->getParameterHolder()->set('max',            null);
    $this->getParameterHolder()->set('max_error',      'The lat / lng is not within range');
    $this->getParameterHolder()->set('max_type',       null);
    $this->getParameterHolder()->set('max_type_error', 'Your lat / lng did not match the specified type');
    $this->getParameterHolder()->set('min',            null);
    $this->getParameterHolder()->set('min_error',     'The lat / lng is not within range');
    $this->getParameterHolder()->set('min_type',       null);
    $this->getParameterHolder()->set('min_type_error', 'Your lat / lng did not match the specified type');
    //$this->getParameterHolder()->set('', null);
 
    $this->getParameterHolder()->add($parameters);
 
    return true;
  }// end function
} // end class myLatLngValidator
 

You use it like so.

  latitude:
    required: 
      msg:  Please enter the latitude or position the marker where your farm is
    myLatLngValidator:
      min: -9
      min_error: Your entered latitude is not within min range
      min_type: '-'
      min_type_error: Your latitude should be in the negative range
      max: -45
      max_error: Your entered latitude is not within max range
      max_type: '-'
      max_type_error: Your latitude should be in the negative range  
 
  longitude:
    required:
      msg: Please enter the longitude or position the marker where your farm is
    myLatLngValidator:
      min: 111
      min_error: Your longitude is not within min range
      min_type: '+'
      min_type_error: Your longitude should be in the positive range
      max: 154
      max_error: Your longitude is not within max range
      max_type: '+'
      max_type_error: Your longitude should be in the positive range
 

I may clean it up in the future. This was so I could constrain the points to be within Australia.

by lionslair on 2008-04-22, tagged latitude  longitude  validator