FormIt: required validation of a field depending on an other field value

It looks like I’m too stupid to write a custom validator.

I have a form (Formit) with radio buttons for choosing “privat” or “commercial”.
And there is a field “birthday”.

If I choose “privat” the “birthday” field should be required; otherwise, it shouldn’t be.

How can I solve this problem?

Here is an example of a custom validator from another thread:

In the snippet code you can access the value of the field (the validator is attached to) with $value, to get the values of other fields use $validator->fields["your_field_name"].

Thanks for the hint, I will give it a try tomorrow. It’s already late today; it’s been a stressful day.

Ok, seems I’m an idiot and don’t understand PHP and/or MODX snippets. Tried this but it fails. I get every time the error message.

[[!FormIt?
	...
	&customValidators=`myCustomValidator`
	&validate=`field1:myCustomValidator`
]]
<form id="myform" action="[[~[[*id]]]]#myform" method="post">  
	...
	<input type="radio" id="green" name="color[]" value="green" [[!+fi.color:FormItIsChecked=`green`]]>
	<label for="green">Green</label>
	<input type="radio" id="red" name="color[]" value="red" [[!+fi.color:FormItIsChecked=`red`]]>
	<label for="red">Red</label>
	<input type="radio" id="blue" name="color[]" value="blue" [[!+fi.color:FormItIsChecked=`blue`]]>
	<label for="blue">Blue</label>
	
	[[!+fi.error.field1]]
	<input type="text" name="field1" value="[[!+fi.field1]]">
	...
</form>

Snippet myCustomValidator

<?php
$success = true;
if (empty(trim($value))){ // field1 is empty
	if ($validator->fields['color'] != 'blue') { // color is not blue
		$success = false;
    }
}

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

The error message should appear if field1 is empty AND color is green OR red. If color is blue field1 can be empty.

With my snippet field1 shows every time ‘fill in field1’.
The error log shows a message: PHP warning: Undefined array key “color”. What can I do now?

I haven’t tested it, but the value of this field is probably an array (['blue']), and not a string ('blue').

Aaah! I got it. Changed

if ($validator->fields['color'] != 'blue')

to

if ($validator->fields['color'] != ['blue'])

and it works!

Many thanks for your help!