Skip to content

Commit

Permalink
[Validator] Add "trim" option to the NotBlankValidator
Browse files Browse the repository at this point in the history
  • Loading branch information
renan-taranto committed Mar 11, 2018
1 parent d1d6e22 commit df450ee
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 1 deletion.
1 change: 1 addition & 0 deletions src/Symfony/Component/Validator/Constraints/NotBlank.php
Expand Up @@ -28,4 +28,5 @@ class NotBlank extends Constraint
);

public $message = 'This value should not be blank.';
public $trim;
}
Expand Up @@ -29,6 +29,8 @@ public function validate($value, Constraint $constraint)
throw new UnexpectedTypeException($constraint, __NAMESPACE__.'\NotBlank');
}

$value = $constraint->trim ? trim($value) : $value;

if (false === $value || (empty($value) && '0' != $value)) {
$this->context->buildViolation($constraint->message)
->setParameter('{{ value }}', $this->formatValue($value))
Expand Down
Expand Up @@ -31,7 +31,7 @@ public function testValidValues($value)

$this->assertNoViolation();
}

public function getValidValues()
{
return array(
Expand All @@ -42,6 +42,17 @@ public function getValidValues()
array(1234),
);
}

public function getWhitespaces()
{
return array(
array("\x20"),
array("\x09"),
array("\x0A"),
array("\x0D"),
array("\x0B"),
);
}

public function testNullIsInvalid()
{
Expand Down Expand Up @@ -98,4 +109,22 @@ public function testEmptyArrayIsInvalid()
->setCode(NotBlank::IS_BLANK_ERROR)
->assertRaised();
}

/**
* @dataProvider getWhitespaces
*/
public function testInvalidTrimmedValues($value)
{
$constraint = new NotBlank(array(
'message' => 'myMessage',
'trim' => true
));

$this->validator->validate($value, $constraint);

$this->buildViolation('myMessage')
->setParameter('{{ value }}', '""')
->setCode(NotBlank::IS_BLANK_ERROR)
->assertRaised();
}
}

0 comments on commit df450ee

Please sign in to comment.