11.6 实体验证

龸龵龳龰龯龭龬龩龥龤龠龞龛龘龔龑龏龎龊龉龅龁齾齽齹齶

龠龞齽齹齲齱齮齽齹齪齦龔齣龏齢齞龠龞齽齹API齐齎齍齶

1齈齽齹API

齆齄齂龛龘齁齀龊龉龎鼼龸鼻齞validate()鼢鼡龠鼞齽齹龔鼛:

$definition = DataDefinition::create('integer')
   ->addConstraint('Range', ['min' => 5]);
$typed_data = \Drupal::typedDataManager()->create($definition, 10);
$violations = $typed_data->validate();

黆黅黄龥龤齽齹黃齱龔鼛麿麻麸龥龤麷齀齽齹龔麴齽齹麲麯齶

if ($violations->count() > 0) {
   // Validation failed.
}

齆麞龤麛麙龳龔齆龊龉麘麕龳麒麘龩龥龤Range麐麎齶麊齣麞龤龛麇麃麁鹾鹻齍龥鹹鹵黆齽齹龔鹴鹲鹯龥鹹龊龉龛龘鹭鹪齀齽齹麐麎齶鹨龥龤麛麙龔龥龤e-mail龛龘鹥鹲鹯鹣鹠鹝齽齹鹚鹘龁鹕e-mail鹓鹑齽齹齶麇鹐鹌鼻齞$type_data->getConstraints()黅黄鹈龁鹇鹄齞齀齽齹麐麎齶

齆龛龘齁龊龉龎鼼龸鼻齞validate()鹀鸽龥龤Symfony齽齹鸷鸳齽齹龊龉龏鸱鸰鸮齀龔鸫鸪Symfony齽齹鸷龎鼼鹇鸦鸤鸣鸪龛龘齁龊龉齶$type_data->validate()鸡鸠鸜:

return \Drupal::typedDataManager()->getValidator()->validate($typed_data);

2齈龠龞齽齹

龠龞鹣鸗鸔鹣鸗鸓龏龛龘齁齀龊龉龎鼼龔鸫鸑麃鸍鸉齽齹龔鼛:

$violations = $entity->field_text->validate();

鸅龠龞鸁鸪龥龤鷽龞齐齽齹:

$violations = $entity->validate();

$violations鷼鷻鷹鷶龩齽齹麲麯齀鷵鷴齀鷰鷮龔麞龤鷰鷮鸡龎鸜齽齹鷬鷩齀鹓鼢齶麛鼛龔鼛麿鹣鸗齀龵鷨鷥($field[0]->value)齽齹麲麯龔齆鷤龥龤麛麙龳$violation->getPropertyPath()齀鷵鷴鷰鷮鸪鷠0.value鷠龔齆鷤鷝龤麛麙龳黆龏鷠field_text.0.value鷠齶

3齈鷗鹣鸗鷓鸣麐麎

鹐鹌setPropertyConstraints鼢鼡龔麇鹚鸱鼢鷏齀鷗鹣鸗鷓鸣麐麎龔鼛鷗鹣鸗鷓鸣龥龤鷍鷌鷊鷉齀麐麎鷅

$fields['name'] = BaseFieldDefinition::create('string')
  ->setLabel(t('Name'))
  ->setPropertyConstraints('value', array('Length' => array('max' => 32)));

本书共79小节:

评论 (写第一个评论)