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;
}
Link: https://gist.github.com/punchi/3a5c44e7aa7ac0609ce9e53365572541
Form ID: 1
Field ID: 1
Bob answers:
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;
}
gutie comments:
Thank you Bob.
It did works perfect!
Arnav Joy answers:
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;
}
gutie comments:
Thank you but it did not work.
I think it should start with:
add_filter( 'gform_field_validation_1_1', 'valida_rut', 10, 4 );
function valida_rut( $result, $value, $form, $field ) {