Drupal form not validating
We then declare two public properties: a message to be used when the constraint fails (with placeholders being populated inside the validator) and the actual code to be checked for (populated by the constructor of the parent class).Inside our constructor, we check if the options passed are a string or array (just to be a bit flexible) and throw an exception if the code parameter is not passed as an option in any shape or form.In our example, we use the constraint for entities, field item lists and primitive data as well. But the is that if a Node entity is passed, the code is checked in its title while for the the field items an iteration is performed to check the values of the fields.
In addition, we will write our own constraint and validator so that we can use custom behaviors in the data validation process.This represents the property path of our violation above.Apart from calling validation on the entire entity (which may be superfluous at times), we can also do so directly on each field: in the violation since we know exactly what we are validating: the first data definition in the list.It’s always better to have constraints targeted to the data definition we want but for the sake of brevity, we’ll do it all in one constraint to see how all these options could be handled.The business case of our example is to have a constraint that we can apply to any string-based content entity field that would force the string to contain a certain alphanumeric code.
It has the expected annotation which, among boilerplate metadata, also specifies what type of data this constraint can be applied to.