Formit custom validator not stopping form submit

<?php
$badwords = array(
'sex',
'girl',
'iPhone',
'giveway',
'win',
'cryptocurrency',
'bitcoin',
'girls',
'sexy',
'viagra',
'cialis',
'generic',
'porno',
'porn',
'Amoxicillin',
'50mg',
'5mg',
'150mg',
'500mg',
'casino online',
'function('
);
    $modx->log(modX::LOG_LEVEL_ERROR, 'validate' );
    $ok = true;

foreach ($badwords as $word) {

if (strpos($value, $word) !== false) {
    $ok = false;
    $modx->log(modX::LOG_LEVEL_ERROR, 'in logic' );
    break;
    }


}

$modx->log(modX::LOG_LEVEL_ERROR, 'value :' .$value);
$modx->log(modX::LOG_LEVEL_ERROR, $ok);
return $ok;

This is a custom validator for formit that is supposed to search for key words in the input values and everything seems to be working correctly except for the fact that it wont stop the form from submitting when it returns false and the error log only shows a blank for the value of $ok when it does

all versions are up to date

Where are you assigning $value ?

please correct me if i am wrong but i believe the validator assigns it to the variable from what i see in this:
https://docs.modx.com/extras/revo/formit/formit.validators#FormIt.Validators-CustomValidators
and in the value that is output in the error log when i run the form with the snippet
@lkfranklin

Ah yeah you may be right. Do you have any better luck if you return false in the if statement instead of break? I’m not a php expert by any means but I think that the break is only ending the if statement and not the foreach, which means that the $ok var is reassigned, but I could be wrong :slight_smile:

No, $ok outputs the same value whether the break statement is in there or not

Try this, I just tested it and it seems to work.

<?php
$badwords = array(
'sex',
'girl',
'iPhone',
'giveway',
'win',
'cryptocurrency',
'bitcoin',
'girls',
'sexy',
'viagra',
'cialis',
'generic',
'porno',
'porn',
'Amoxicillin',
'50mg',
'5mg',
'150mg',
'500mg',
'casino online',
'function('
);

foreach ($badwords as $word) {
	if (strpos($value, $word) !== false) {
	    $modx->log(modX::LOG_LEVEL_ERROR, 'Bad word found: ' . $value);
	    $validator->addError($key,'Bad words!');
	}
}

$modx->log(modX::LOG_LEVEL_ERROR, 'No bad words found. Submitting form.');
return true;
1 Like

yeah it was because i wasn’t throwing the error. Apparently its the error that stops the submit not the return false…

1 Like

This topic was automatically closed 2 days after discussion ended and a solution was marked. New replies are no longer allowed. You can open a new topic by clicking the link icon below the original post or solution and selecting “+ New Topic”.