type(), self::TYPES, true ); } /** * Checks the submitted choices against the field. * * @param Field $field Field being validated. * @param mixed $value Sanitised value. * * @return ValidationError|null The failure, or null when the value passes. */ public function validate( Field $field, mixed $value ): ?ValidationError { $allowed = array(); foreach ( $field->options() as $option ) { $allowed[] = (string) ( $option['value'] ?? '' ); } foreach ( (array) $value as $item ) { if ( ! in_array( (string) $item, $allowed, true ) ) { return new ValidationError( '', 'invalid_choice', __( 'Please choose one of the available options.', 'devplugins-custom-form-builder' ) ); } } return $this->check_count( $field, (array) $value ); } /** * Checks how many choices were made against the configured limits. * * @param Field $field Field being validated. * @param array $selected Submitted choices. * * @return ValidationError|null The failure, or null when the count is acceptable. */ private function check_count( Field $field, array $selected ): ?ValidationError { $count = count( $selected ); $min = (int) $field->setting( 'min_choices', 0 ); $max = (int) $field->setting( 'max_choices', 0 ); if ( $min > 0 && $count < $min ) { return new ValidationError( '', 'too_few_choices', sprintf( /* translators: %s: Smallest number of choices required. */ _n( 'Please choose at least %s option.', 'Please choose at least %s options.', $min, 'devplugins-custom-form-builder' ), number_format_i18n( $min ) ), array( 'min' => $min ) ); } if ( $max > 0 && $count > $max ) { return new ValidationError( '', 'too_many_choices', sprintf( /* translators: %s: Largest number of choices allowed. */ _n( 'Please choose no more than %s option.', 'Please choose no more than %s options.', $max, 'devplugins-custom-form-builder' ), number_format_i18n( $max ) ), array( 'max' => $max ) ); } return null; } }