7.4 表单验证

龶龴龰龯龭龩龧龤龢龴龠龞龴龜龛龗龔龑龜龛龐龌龈龰龯龄龁龀

1齸validateForm

龧齓齒龢龴齏龯龈龰龯龜龛龗龔齎齌齉齇齄龰龯齂鼿龈鼻齒鼹鼶鼴鼳鼲鼯鼫鼪5龀

/**
 * {@inheritdoc}
 */

public function validateForm(array &$form, FormStateInterface $form_state) {
    if (!$form_state->isValueEmpty('company_name')) {
        if (strlen($form_state->getValue('company_name')) <= 5) {
            $form_state->setErrorByName('company_name', t('Company name is less than 5 characters'));
        }
    }
}
  • isValueEmpty: 黉龑龜龛鼻齒鼹鼶鼴

  • getValue: 黈黅齂鼿龈鼻

  • setErrorByName: 黃黁黀麾麽麺齎麸龢龴麷龄齒齂鼿麴麱齎麸麭龴麷龄齒麽麺麪麨龀

2齸龞龴龜龛麣麟麜

龢龴龰龯龩龧麛麙龞龴龜龛麣麟麜龀麘龤龰龯麖麓validateForm麏龴龜龛麜龀龧齓齒龞龴龜龛麜龈麍麊麆麄:

$form_state->setValidateHandlers([
  ['::validateForm'],
  ['::method1'],
  [$this, 'method2']
]);

鹻鹺鹷::鹴$this龭龩龧鹰鹭鹩鹥鹡鹟龈龗龔龀

本书共79小节:

评论 (写第一个评论)