Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit df450ee

Browse files
committed
[Validator] Add "trim" option to the NotBlankValidator
1 parent d1d6e22 commit df450ee

File tree

3 files changed

+33
-1
lines changed

3 files changed

+33
-1
lines changed

src/Symfony/Component/Validator/Constraints/NotBlank.php

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,4 +28,5 @@ class NotBlank extends Constraint
2828
);
2929

3030
public $message = 'This value should not be blank.';
31+
public $trim;
3132
}

src/Symfony/Component/Validator/Constraints/NotBlankValidator.php

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,8 @@ public function validate($value, Constraint $constraint)
2929
throw new UnexpectedTypeException($constraint, __NAMESPACE__.'\NotBlank');
3030
}
3131

32+
$value = $constraint->trim ? trim($value) : $value;
33+
3234
if (false === $value || (empty($value) && '0' != $value)) {
3335
$this->context->buildViolation($constraint->message)
3436
->setParameter('{{ value }}', $this->formatValue($value))

src/Symfony/Component/Validator/Tests/Constraints/NotBlankValidatorTest.php

Lines changed: 30 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,7 @@ public function testValidValues($value)
3131

3232
$this->assertNoViolation();
3333
}
34-
34+
3535
public function getValidValues()
3636
{
3737
return array(
@@ -42,6 +42,17 @@ public function getValidValues()
4242
array(1234),
4343
);
4444
}
45+
46+
public function getWhitespaces()
47+
{
48+
return array(
49+
array("\x20"),
50+
array("\x09"),
51+
array("\x0A"),
52+
array("\x0D"),
53+
array("\x0B"),
54+
);
55+
}
4556

4657
public function testNullIsInvalid()
4758
{
@@ -98,4 +109,22 @@ public function testEmptyArrayIsInvalid()
98109
->setCode(NotBlank::IS_BLANK_ERROR)
99110
->assertRaised();
100111
}
112+
113+
/**
114+
* @dataProvider getWhitespaces
115+
*/
116+
public function testInvalidTrimmedValues($value)
117+
{
118+
$constraint = new NotBlank(array(
119+
'message' => 'myMessage',
120+
'trim' => true
121+
));
122+
123+
$this->validator->validate($value, $constraint);
124+
125+
$this->buildViolation('myMessage')
126+
->setParameter('{{ value }}', '""')
127+
->setCode(NotBlank::IS_BLANK_ERROR)
128+
->assertRaised();
129+
}
101130
}

0 commit comments

Comments
 (0)