Skip to content

Commit

Permalink
Fix html validation for checkboxes
Browse files Browse the repository at this point in the history
Use `this.checked` instead of `this.value` for checkboxes as
we want to validate that checkboxes are checked as their value is fixed.

Port changes from #17683 to 5.x

Fixes #17672
  • Loading branch information
markstory committed May 13, 2024
1 parent 160652e commit c708617
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 1 deletion.
6 changes: 5 additions & 1 deletion src/View/Helper/FormHelper.php
Original file line number Diff line number Diff line change
Expand Up @@ -1426,9 +1426,13 @@ protected function setRequiredAndCustomValidity(string $fieldName, array $option
$options['templateVars']['customValidityMessage'] = $message;

if ($this->getConfig('autoSetCustomValidity')) {
$condition = 'this.value';
if ($options['type'] === 'checkbox') {
$condition = 'this.checked';
}
$options['data-validity-message'] = $message;
$options['oninvalid'] = "this.setCustomValidity(''); "
. 'if (!this.value) this.setCustomValidity(this.dataset.validityMessage)';
. "if (!{$condition}) this.setCustomValidity(this.dataset.validityMessage)";
$options['oninput'] = "this.setCustomValidity('')";
}
}
Expand Down
23 changes: 23 additions & 0 deletions tests/TestCase/View/Helper/FormHelperTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -7834,6 +7834,7 @@ public function testHtml5ErrorMessage(): void
->notEmptyString('email', 'Custom error message')
->requirePresence('password')
->alphaNumeric('password')
->requirePresence('accept_tos')
->notBlank('phone');

$table = $this->getTableLocator()->get('Contacts', [
Expand Down Expand Up @@ -7903,6 +7904,28 @@ public function testHtml5ErrorMessage(): void
],
];
$this->assertHtml($expected, $result);

$result = $this->Form->control('accept_tos', ['type' => 'checkbox']);
$expected = [
['input' => ['type' => 'hidden', 'name' => 'accept_tos', 'value' => '0']],
'label' => ['for' => 'accept-tos'],
[
'input' => [
'aria-required' => 'true',
'required' => 'required',
'type' => 'checkbox',
'name' => 'accept_tos',
'id' => 'accept-tos',
'value' => '1',
'data-validity-message' => 'This field cannot be left empty',
'oninput' => 'this.setCustomValidity('')',
'oninvalid' => 'this.setCustomValidity(''); if (!this.checked) this.setCustomValidity(this.dataset.validityMessage)',
],
],
'Accept Tos',
'/label',
];
$this->assertHtml($expected, $result);
}

/**
Expand Down

0 comments on commit c708617

Please sign in to comment.