FIX: NumericField should work with numbers like 54,6

Fixes http://open.silverstripe.org/ticket/5577.

Uses Zend_Locale_Format::isNumber(). Includes unit test for NumericField. Does not include testing work on DBField underlying NumericField to ensure that works consistently.
This commit is contained in:
Will Rossiter 2013-05-11 22:51:39 +12:00
parent d6733caf14
commit a99dbae012
2 changed files with 55 additions and 7 deletions

View File

@ -1,19 +1,29 @@
<?php <?php
/** /**
* Text input field with validation for numeric values. * Text input field with validation for numeric values. Supports validating
* the numeric value as to the {@link i18n::get_locale()} value.
* *
* @package forms * @package forms
* @subpackage fields-formattedinput * @subpackage fields-formattedinput
*/ */
class NumericField extends TextField{ class NumericField extends TextField {
public function Type() { public function Type() {
return 'numeric text'; return 'numeric text';
} }
/** PHP Validation **/ public function validate($validator) {
public function validate($validator){ if(!$this->value && !$validator->fieldIsRequired($this->name)) {
if($this->value && !is_numeric(trim($this->value))){ return true;
}
$valid = Zend_Locale_Format::isNumber(
trim($this->value),
array('locale' => i18n::get_locale())
);
if(!$valid) {
$validator->validationError( $validator->validationError(
$this->name, $this->name,
_t( _t(
@ -22,10 +32,11 @@ class NumericField extends TextField{
), ),
"validation" "validation"
); );
return false; return false;
} else{
return true;
} }
return true;
} }
public function dataValue() { public function dataValue() {

View File

@ -0,0 +1,37 @@
<?php
/**
* @package framework
* @subpackage tests
*/
class NumericFieldTest extends SapphireTest {
protected $usesDatabase = false;
public function testValidator() {
i18n::set_locale('en_US');
$field = new NumericField('Number');
$field->setValue('12.00');
$validator = new RequiredFields('Number');
$this->assertTrue($field->validate($validator));
$field->setValue('12,00');
$this->assertFalse($field->validate($validator));
$field->setValue('0');
$this->assertTrue($field->validate($validator));
$field->setValue(false);
$this->assertFalse($field->validate($validator));
i18n::set_locale('de_DE');
$field->setValue('12,00');
$validator = new RequiredFields();
$this->assertTrue($field->validate($validator));
$field->setValue('12.00');
$this->assertFalse($field->validate($validator));
}
}