Skip to content

Instantly share code, notes, and snippets.

@furkantektas
Created September 12, 2014 14:30
Show Gist options
  • Save furkantektas/d7dcd2ac63319049ccd8 to your computer and use it in GitHub Desktop.
Save furkantektas/d7dcd2ac63319049ccd8 to your computer and use it in GitHub Desktop.
Yii location validator. Sample Location: 41 29
<?php
/**
* PointValidator class for Yii.
* Author: Furkan Tektas github.com/furkantektas
* Date: 2014/09/05
* Version: v1.0
*/
class PointValidator extends CValidator
{
/**
* @var boolean whether the attribute value can be null or empty. Defaults to true,
* meaning that if the attribute is empty, it is considered valid.
*/
public $allowEmpty=true;
// regex only accepts locations begins with floating number
// any number of whitespaces and another floating point.
// String should be trimmed before matching.
const VALIDATOR_REGEX = "/^(\-?\d+(\.\d+)?)[[:blank:]]+(\-?\d+(\.\d+)?)$/";
/**
* @inheritDoc
*/
public function validateAttribute($object, $attribute)
{
if($this->allowEmpty && $this->isEmpty($object->$attribute))
return;
if(!preg_match(PointValidator::VALIDATOR_REGEX,trim($object->{$attribute}))) {
$message = Yii::t('app', 'The point\'s coordinates are not valid!');
$this->addError($object, $attribute, $message);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment