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小节:

评论 (写第一个评论)