silverstripe-framework/forms/NumericField.php
Ingo Schommer c0a7241812 BUGFIX Fixing NumericField serverside validation to accept numbers with leading or trailing spaces by using trim()
git-svn-id: svn://svn.silverstripe.com/silverstripe/open/modules/sapphire/branches/2.3@74721 467b73ca-7a2a-4603-9d3b-597d59a354a9
2011-02-02 14:27:14 +13:00

65 lines
1.5 KiB
PHP
Executable File

<?php
/**
* A Single Numeric field extending a typical
* TextField but with validation.
* @package forms
* @subpackage fields-formattedinput
*/
class NumericField extends TextField{
function jsValidation() {
$formID = $this->form->FormName();
$error = _t('NumericField.VALIDATIONJS', 'is not a number, only numbers can be accepted for this field');
$jsFunc =<<<JS
Behaviour.register({
"#$formID": {
validateNumericField: function(fieldName) {
el = _CURRENT_FORM.elements[fieldName];
if(!el || !el.value) return true;
if(el.value.match(/^\s*([0-9]+(\.[0-9]+)?\s*$)/)) {
return true;
} else {
validationError(el, "'" + el.value + "' $error","validation");
return false;
}
}
}
});
JS;
Requirements::customScript($jsFunc, 'func_validateNumericField');
//return "\$('$formID').validateNumericField('$this->name');";
return <<<JS
if(typeof fromAnOnBlur != 'undefined'){
if(fromAnOnBlur.name == '$this->name')
$('$formID').validateNumericField('$this->name');
}else{
$('$formID').validateNumericField('$this->name');
}
JS;
}
/** PHP Validation **/
function validate($validator){
if($this->value && !is_numeric(trim($this->value))){
$validator->validationError(
$this->name,
sprintf(
_t('NumericField.VALIDATION', "'%s' is not a number, only numbers can be accepted for this field"),
$this->value
),
"validation"
);
return false;
} else{
return true;
}
}
function dataValue() {
return (is_numeric($this->value)) ? $this->value : 0;
}
}
?>