Formit, require at least one of two fields

I am trying to make a form where at least one of two fields is required. I found this (Bruno’s solution): https://forums.modx.com/thread/87971/formit-validators-required-one-of-2-fields-possible

I changed it into this and use it as a custom validator:

<?php $validations = array(); $validations['gross_income'] = 'required:gross_income'; $validations['netto_income'] = 'required:netto_income'; $gross_income = $modx->getOption('gross_income',$_REQUEST); $netto_income = $modx->getOption('netto_income',$_REQUEST); if (!empty($gross_income)){ unset($validations['gross_income']); } if (!empty($netto_income)){ unset($validations['netto_income']); } $validate = array(); foreach ($validatons as $field=>$validation){ $validate[] = $field . ':' . $validation; } $scriptProperties['validate'] = implode(',',$validate);

Bruno’s solution is not supposed to be a custom validator.
It’s a way to “wrap FormIt inside a custom-snippet” and create the &validate property on the fly.


In a custom validator just read the 2 values with $validator->fields["your_field_name"]. Check if at least one of them is not empty and return true or false.

Thanks for the tip but how do I do that, I have no experience with writing scripts for custom validators.

Something like this should work:

[[!FormIt?
   ...
   &customValidators=`myCustomValidator`
   &validate=`field1:myCustomValidator`
]]
<form id="myform" action="[[~[[*id]]]]#myform" method="post">   
   [[!+fi.error.field1]]
   <input type="text" name="field1" value="[[!+fi.field1]]">
   <input type="text" name="field2" value="[[!+fi.field2]]">
   ...
</form>

Snippet myCustomValidator

<?php
$success = true;
if (empty(trim($value))){ // field1 is empty
    if (isset($validator->fields["field2"])){
        if (empty(trim($validator->fields["field2"]))){ // field2 is empty
            $success = false;
        }
    } else {
        $success = false;
    }
}

if (!$success) {
    $validator->addError($key,'Please fill in either field1 or field2!');
}
return $success;

You are a hero, thanks!!!