Implement validate() method for TextField to validate max length (closes #4073)

This commit is contained in:
Kamran Vighio 2015-05-16 01:46:54 +02:00 committed by Loz Calver
parent a2ecb3f086
commit 20c9d6f02e
3 changed files with 53 additions and 0 deletions

View File

@ -52,4 +52,26 @@ class TextField extends FormField {
return $this->Field();
}
/**
* Validate this field
*
* @param Validator $validator
* @return bool
*/
public function validate($validator) {
if(!is_null($this->maxLength) && mb_strlen($this->value) > $this->maxLength) {
$validator->validationError(
$this->name,
_t(
'TextField.VALIDATEMAXLENGTH',
'The value for {name} must not exceed {maxLength} characters in length',
array('name' => $this->getName(), 'maxLength' => $this->maxLength)
),
"validation"
);
return false;
}
return true;
}
}

View File

@ -548,6 +548,8 @@ en:
Print: Print
TableListField_PageControls_ss:
OF: of
TextField:
VALIDATEMAXLENGTH: 'The value for {name} must not exceed {maxLength} characters in length'
TimeField:
VALIDATEFORMAT: 'Please enter a valid time format ({format})'
ToggleField:

View File

@ -0,0 +1,29 @@
<?php
/**
* @package framework
* @subpackage tests
*/
class TextFieldTest extends SapphireTest {
/**
* Tests the TextField Max Length Validation Failure
*/
public function testMaxLengthValidationFail() {
$textField = new TextField('TestField');
$textField->setMaxLength(5);
$textField->setValue("John Doe"); // 8 characters, so should fail
$result = $textField->validate(new RequiredFields());
$this->assertFalse($result);
}
/**
* Tests the TextField Max Length Validation Success
*/
public function testMaxLengthValidationSuccess() {
$textField = new TextField('TestField');
$textField->setMaxLength(5);
$textField->setValue("John"); // 4 characters, so should pass
$result = $textField->validate(new RequiredFields());
$this->assertTrue($result);
}
}