3

I'm looking at this guide to writing custom validators: https://experiencehq.net/blog/the-definitive-guide-to-validation-in-craft-part-5-custom-validators

However, this only allows code that refers to the current field. The comparison validators exist so I know it's possible. I want to do a CVV and credit card number validator that check against the credit card type, and also make some fields conditionally required.

In this example only the attribute itself is referred to:

public function validateUsername($attribute)
{
    $value = $this->$attribute;

    if ($value && strtolower($value) == 'spartacus') {
        $message = Craft::t("No, I'm Spartcus!");
        $this->addError($attribute, $message);
    }
}

How do I refer to another field in the model in my validator?

2

Looks like I can just refer to the other field name:

public function validateUsername($attribute)
{
    $value = $this->$attribute;
    $otherFieldsValue = $this->otherField;

    if ($value && strtolower($otherFieldsValue) == 'spartacus') {
        $message = Craft::t("No, I'm Spartcus!");
        $this->addError($attribute, $message);
    }
}
| improve this answer | |

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.