From 20c9d6f02e1c45f8ac9926d167558687e35fb446 Mon Sep 17 00:00:00 2001 From: Kamran Vighio Date: Sat, 16 May 2015 01:46:54 +0200 Subject: [PATCH] Implement validate() method for TextField to validate max length (closes #4073) --- forms/TextField.php | 22 ++++++++++++++++++++++ lang/en.yml | 2 ++ tests/forms/TextFieldTest.php | 29 +++++++++++++++++++++++++++++ 3 files changed, 53 insertions(+) create mode 100644 tests/forms/TextFieldTest.php diff --git a/forms/TextField.php b/forms/TextField.php index 1d54c5b2b..885418ccb 100644 --- a/forms/TextField.php +++ b/forms/TextField.php @@ -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; + } + } diff --git a/lang/en.yml b/lang/en.yml index cb09c0646..2d5097e11 100644 --- a/lang/en.yml +++ b/lang/en.yml @@ -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: diff --git a/tests/forms/TextFieldTest.php b/tests/forms/TextFieldTest.php new file mode 100644 index 000000000..7be2f3666 --- /dev/null +++ b/tests/forms/TextFieldTest.php @@ -0,0 +1,29 @@ +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); + } +}