Sterc / FormIt

A dynamic form processing Snippet for MODX Revolution
https://docs.modx.com/current/en/extras/formit
33 stars 58 forks source link

"required" validator allows strings with only spaces through #11

Closed valZho closed 9 years ago

valZho commented 10 years ago

I can't think of a use-case on a web-form where a spaces-only entry would count as not empty (note: just because I can't think of it doesn't mean it doesn't exist).

I suggest performing a trim() on the value before testing for empty() to bounce back spaces-only entries:

public function required($key,$value) {
        $success = false;
        if (is_array($value) && isset($_FILES[$key])) { /* handling file uploads */
            $success = !empty($value['tmp_name']) && isset($value['error']) && $value['error'] == UPLOAD_ERR_OK ? true : false;
        } else {
            $v = trim($value,' ');
            $success = (!empty($v) || is_numeric($v)) ? true : false;
        }
        return $success ? true : $this->_getErrorMessage($key,'vTextRequired','formit.field_required',array(
            'field' => $key,
            'value' => is_array($value) ? implode(',',$value) : $value,
        ));
    }
pixelchutes commented 10 years ago

I find myself having to use a custom hook to circumvent FormIt's built-in required validator allowing only whitespace entries as valid.

Here's an example of a custom hook to achieve this: confirmValid hook:

$value = preg_replace( '/\s+/', '', $value ); // Strip whitespace
$success = strlen( $value ) > 0; // Does something valid exist?
if( !$success ) {
    // Add an error to the field
    $validator->addError( $key, 'Please enter a valid value.' ); // Optionally substitute with formit.field_required lexicon here
}
return $success;

I agree with you, the built-in required validator should probably be accounting for this already.