contact-form
contact-form copied to clipboard
Cant get addError to work $submission->addError('message.body', 'Links are not allowed in the message');
Does the addError on a custom field actually work? Here is my code to check if links are in the body and if so to show an error:
Event::on(Submission::class, Submission::EVENT_AFTER_VALIDATE, function(Event $e)
{
$submission = $e->sender;
if( isset($submission->message['body']) )
{
$message = $submission->message['body'];
if( strpos($message, 'https:') !== false || strpos($message, 'http:') !== false || strpos($message, 'www.') !== false )
{
$submission->addError('message.body', 'Links are not allowed in the message');
}
}
});
Then in the template:
<textarea rows="6" cols="40" id="message" name="message[body]" placeholder="{{ strings('Inquiry') }}" required>{{ message.message.body ?? '' }}</textarea>
{{ message is defined and message ? errorList(message.getErrors('message.body')) }}
Although the flash error message appears saying there are errors with the form, the specific error after the text area is not showing. I was referring to the documentation on The afterValidate event, but using my body field instead of Phone in the example. Cant see any other differences.
The $submission object does not contain the above error
If I leave my email blank I can see the built in error for email is required. So it seems this is just not working:
$submission->addError('message.body', 'Links are not allowed in the message');
Came here to ask a similar question.
It seems that the default required fields (body, fromEmail) have set error messages. I haven't delved into the source yet, but will try to remember to update this comment when I do
Hi, apologies for the late reply!
I just tested this with the latest versions (Craft CMS 3.9.11 + Contact Form 2.5.2 and Craft CMS 4.8.1 + Contact Form 3.0.1), and in both cases, adding an error to a custom field (via addError()
) works as expected.
I will close this, but if you still have issues with those not showing, please don’t hesitate to get in touch.