<p>Looks like I can just refer to the other field name: </p>

<pre><code>public function validateUsername($attribute)
{
    $value = $this-&gt;$attribute;
    $otherFieldsValue = $this-&gt;otherField;

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

CC BY-SA 3.0
2016-05-30T20:17:33.930Z
2016-05-30T20:17:33.930Z
danieltalsky
<p>I'm looking at this guide to writing custom validators:
<a href="https://experiencehq.net/blog/the-definitive-guide-to-validation-in-craft-part-5-custom-validators" rel="nofollow">https://experiencehq.net/blog/the-definitive-guide-to-validation-in-craft-part-5-custom-validators</a></p>

<p>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.</p>

<p>In this example only the attribute itself is referred to:</p>

<pre><code>public function validateUsername($attribute)
{
    $value = $this-&gt;$attribute;

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

<p>How do I refer to another field in the model in my validator?</p>

<plugin-development><validation><models>
How do I write custom model validators for my plugin that refer to other fields?
# How do I write custom model validators for my plugin that refer to other fields?

(Asked by: username_0 on 2016-05-28)

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?

**Tags:** plugin-development, validation, models


---

## 1 answers

### Answer by username_0 on 2016-05-30. Score: 2 | Accepted answer

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);
    }
}


---

