Trying to figure out custom validation with constraints, but no luck yet. Right now, my form posts content and gives no errors when form is filled out incorrectly.
(Please avoid suggesting validation modules — I know those exist.)
Maybe somebody knows what I’m missing? Or maybe it’s done different when I’m doing specific fields? Or maybe this isn’t how to do it on a back-end content submission form? Here’s what I have so far:
I built a module called “custom_validation.” It contains custom_validation.module:
<?php /** * @file */ /** * Implements hook_entity_type_alter(). */ function custom_validation_entity_type_alter(array &$entity_types) { /** @var $entity_types DrupalCoreEntityEntityTypeInterface[] */ $entity = $entity_types['node']; $entity->addConstraint('BlogpostError'); }
Then, in subfolder src/Plugin/Validation/Constraint, I’ve got two files. BlogpostErrorConstraint.php contains:
namespace Drupalcustom_validationPluginValidationConstraint; use SymfonyComponentValidatorConstraint; /** * Prevent article creation if errors. * * @Constraint( * id = "BlogpostError", * label = @Translation("Added blog post category instead of story author in author field", context = "Validation"), * type = "string" * ) */ class BlogpostErrorConstraint extends Constraint { /** * {@inheritdoc} */ public $notByline = '%value is a blog post type. Please add a byline'; public $noImageSource = 'need image source'; }
BlogpostErrorConstraintValidator.php contains:
namespace Drupalcustom_validationPluginValidationConstraint; use SymfonyComponentValidatorConstraint; use SymfonyComponentValidatorConstraintValidator; /** * Validates the BlogpostError constraint. */ class BlogpostErrorConstraintValidator extends ConstraintValidator { /** * {@inheritdoc} */ public function validate($items, Constraint $constraint) { if (!isset($items)) { return; } // limit this to 'blog entries' content type if ($items->bundle() == 'blog_entry') { // now loop through each field... foreach ($items as $delta => $item) { // an array of phrases we don't want in the field $bad_bylines = []; array_push($bad_bylines,"Value one","value two","abc123"); // adding validation... //byline field if (in_array($item['field_byline'], $bad_bylines)) { // not sure of syntax here $this->context->addViolation($constraint->notByline, ['%value' => $item->value]); } //main image source field... if ($item['field_main_image_source'] == '') { $this->context->addViolation($constraint->noImageSource, ['%value' => $item->value]); } } } } }