1: 2: 3: 4: 5: 6: 7: 8: 9: 10: 11: 12: 13: 14: 15: 16: 17: 18: 19: 20: 21: 22: 23: 24: 25: 26: 27: 28: 29: 30: 31: 32: 33: 34: 35: 36: 37: 38: 39: 40: 41: 42: 43: 44: 45: 46: 47: 48: 49: 50: 51: 52: 53: 54: 55: 56: 57: 58: 59: 60: 61: 62: 63: 64: 65: 66: 67: 68: 69: 70: 71: 72: 73: 74: 75: 76: 77: 78: 79: 80: 81: 82: 83: 84: 85: 86: 87:
<?php
namespace MvcCore\Ext\Form\Validators;
require_once(__DIR__.'/../../Form.php');
require_once(__DIR__.'/../Core/Validator.php');
require_once(__DIR__.'/../Core/Field.php');
require_once(__DIR__.'/../Core/View.php');
use
MvcCore\Ext\Form,
MvcCore\Ext\Form\Core;
class NumberField extends Core\Validator
{
public function Validate ($submitValue, $fieldName, \MvcCore\Ext\Form\Core\Field & $field) {
$submitValue = trim((string) $submitValue);
$intValueStr = preg_replace("#[^0-9]#", '', $submitValue);
$floatValueStr = preg_replace("#[^0-9\.]#", '', str_replace(',','.',$submitValue));
$errorMsgKeyCommon = '';
$errorMsgKey = '';
if (strlen($intValueStr) === 0) {
if ($field->Required) $errorMsgKey = Form::NUMBER;
$safeValue = '';
} else {
if ($floatValueStr === $intValueStr) {
$safeValue = intval($intValueStr);
$errorMsgKeyCommon = Form::INTEGER;
} else {
$safeValue = floatval($intValueStr);
$errorMsgKeyCommon = Form::FLOAT;
}
$errorMsgKey = '';
if (isset($this->Min) && !is_null($field->Min)) {
if ($safeValue < $field->Min) {
$errorMsgKey = !is_null($this->Max) ? Form::RANGE : Form::GREATER;
}
}
if (isset($this->Max) && !is_null($this->Max)) {
if ($safeValue > $field->Max) {
$errorMsgKey = !is_null($this->Min) ? Form::RANGE : Form::LOWER;
}
}
if (isset($this->Pattern) && !is_null($this->Pattern)) {
preg_match("#^".$this->Pattern."$#", (string)$safeValue, $matches);
if (!$matches) {
$errorMsgKey = $errorMsgKeyCommon;
}
}
}
if (mb_strlen($safeValue) !== mb_strlen($submitValue) || $errorMsgKey) {
$errorMsgKey = $errorMsgKey ? $errorMsgKey : $errorMsgKeyCommon ;
$errorReplacements = array();
if ($errorMsgKey == Form::RANGE) {
$errorReplacements[] = $field->Min;
$errorReplacements[] = $field->Max;
} else if ($errorMsgKey == Form::GREATER) {
$errorReplacements[] = $field->Min;
} else if ($errorMsgKey == Form::LOWER) {
$errorReplacements[] = $field->Max;
}
$this->addError(
$field,
Form::$DefaultMessages[$errorMsgKey],
function ($msg, $args) use (& $errorReplacements) {
$args = array_merge($args, $errorReplacements);
return Core\View::Format($msg, $args);
}
);
}
return $safeValue;
}
}