mirror of
https://github.com/silverstripe/silverstripe-framework
synced 2024-10-22 14:05:37 +02:00
Implement validate() method for TextField to validate max length (closes #4073)
This commit is contained in:
parent
a2ecb3f086
commit
20c9d6f02e
@ -52,4 +52,26 @@ class TextField extends FormField {
|
|||||||
return $this->Field();
|
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;
|
||||||
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
@ -548,6 +548,8 @@ en:
|
|||||||
Print: Print
|
Print: Print
|
||||||
TableListField_PageControls_ss:
|
TableListField_PageControls_ss:
|
||||||
OF: of
|
OF: of
|
||||||
|
TextField:
|
||||||
|
VALIDATEMAXLENGTH: 'The value for {name} must not exceed {maxLength} characters in length'
|
||||||
TimeField:
|
TimeField:
|
||||||
VALIDATEFORMAT: 'Please enter a valid time format ({format})'
|
VALIDATEFORMAT: 'Please enter a valid time format ({format})'
|
||||||
ToggleField:
|
ToggleField:
|
||||||
|
29
tests/forms/TextFieldTest.php
Normal file
29
tests/forms/TextFieldTest.php
Normal 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);
|
||||||
|
}
|
||||||
|
}
|
Loading…
Reference in New Issue
Block a user