2

What is the cleanest way to validate if a checkbox (i.e. agree to legal terms) is checked?

3

There's no clean way doing this without making changes to the plugin itself. The contactForm.beforeSend event makes it possible to prevent the email from being sent from another plugin, but you're only being passed the compiled email message as a string. It's probably possible to post you checkbox data with that string and parse for it in your event listener, but you asked for a clean solution! :)

So fork the plugin and add a new attribute to the ContactFormModel:

'agreedToTerms' => array(AttributeType::Enum, 'required' => true, 'values' => array(true)),

And make the ContactFormController get the attribute value from your form:

$message->agreedToTerms = craft()->request->getPost('agreedToTerms');

You're now all set add a checkbox "agreedToTerms" to your form and add a custom error message in case the model attribute failed validation:

<label><input type="checkbox" name="agreedToTerms" value="true" {{ message is defined and message.agreedToTerms ? 'checked' }}> Agree the Terms and Conditions</label>

{% if message is defined and message.hasErrors('agreedToTerms') %}
    <ul class="errors"><li>{{ 'You must agree the Terms and Conditions'|t }}</li></ul>
{% endif %}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.