# Gravity Form Function Validation

• SOLVED

I want to use a custom PHP function in Gravity Forms to validate an input text field.

This is the function:

function valida_rut(\$rut)
{
if (!preg_match("/^[0-9.]+[-]?+[0-9kK]{1}/", \$rut)) {
return false;
}
\$rut = preg_replace('/[\.\-]/i', '', \$rut);
\$dv = substr(\$rut, -1);
\$numero = substr(\$rut, 0, strlen(\$rut) - 1);
\$i = 2;
\$suma = 0;
foreach (array_reverse(str_split(\$numero)) as \$v) {
if (\$i == 8)
\$i = 2;
\$suma += \$v * \$i;
++\$i;
}
\$dvr = 11 - (\$suma % 11);
if (\$dvr == 11)
\$dvr = 0;
if (\$dvr == 10)
\$dvr = 'K';
if (\$dvr == strtoupper(\$dv))
return true;
else
return false;
}

Form ID: 1
Field ID: 1

2017-02-08

``` public function valida_rut(\$rut) { if (!preg_match("/^[0-9.]+[-]?+[0-9kK]{1}/", \$rut)) { return false; } \$rut = preg_replace('/[\.\-]/i', '', \$rut); \$dv = substr(\$rut, -1); \$numero = substr(\$rut, 0, strlen(\$rut) - 1); \$i = 2; \$suma = 0; foreach (array_reverse(str_split(\$numero)) as \$v) { if (\$i == 8) \$i = 2; \$suma += \$v * \$i; ++\$i; } \$dvr = 11 - (\$suma % 11); if (\$dvr == 11) \$dvr = 0; if (\$dvr == 10) \$dvr = 'K'; if (\$dvr == strtoupper(\$dv)) return true; else return false; } add_filter( 'gform_validation_1', 'custom_validation' ); function custom_validation( \$validation_result ) { \$form = \$validation_result['form']; //validate input 1 with desired function valida_rut if ( valida_rut( rgpost( 'input_1' ) ) == false ) { // set the form validation to false \$validation_result['is_valid'] = false; //finding Field with ID of 1 and marking it as failed validation foreach( \$form['fields'] as &\$field ) { //NOTE: replace 1 with the field you would like to validate if ( \$field->id == '1' ) { \$field->failed_validation = true; \$field->validation_message = 'This field is invalid!'; break; } } } //Assign modified \$form object back to the validation result \$validation_result['form'] = \$form; return \$validation_result; } ```

Thank you Bob.
It did works perfect!

2017-02-08

try this

``` <?php function valida_rut(\$rut) { if (!preg_match("/^[0-9.]+[-]?+[0-9kK]{1}/", \$rut)) { return false; } \$rut = preg_replace('/[\.\-]/i', '', \$rut); \$dv = substr(\$rut, -1); \$numero = substr(\$rut, 0, strlen(\$rut) - 1); \$i = 2; \$suma = 0; foreach (array_reverse(str_split(\$numero)) as \$v) { if (\$i == 8) \$i = 2; \$suma += \$v * \$i; ++\$i; } \$dvr = 11 - (\$suma % 11); if (\$dvr == 11) \$dvr = 0; if (\$dvr == 10) \$dvr = 'K'; if (\$dvr == strtoupper(\$dv)) return true; else return false; } add_filter( 'gform_validation_1', 'aj_validate' ); function aj_validate( \$form ) { \$valida_rut = valida_rut( rgpost( 'input_1' ) ); return \$valida_rut; } ```