How can i use this code for validate a element?

juancarlos

New Member
Hi,

i have a element called "rut" (Without " "). I need validate that this element with this code. So i create a validation php in element rut, i use return true; like conditi?n and this code.

PHP:
function validaRut($rut){
    if(strpos($rut,"-")==false){
        $RUT[0] = substr($rut, 0, -1);
        $RUT[1] = substr($rut, -1);
    }else{
        $RUT = explode("-", trim($rut));
    }
    $elRut = str_replace(".", "", trim($RUT[0]));
    $factor = 2;
    for($i = strlen($elRut)-1; $i >= 0; $i--):
        $factor = $factor > 7 ? 2 : $factor;
        $suma += $elRut{$i}*$factor++;
    endfor;
    $resto = $suma % 11;
    $dv = 11 - $resto;
    if($dv == 11){
        $dv=0;
    }else if($dv == 10){
        $dv="k";
    }else{
        $dv=$dv;
    }
  if($dv == trim(strtolower($RUT[1]))){
      return true;
  }else{
      return false;
  }
}

I only change the var $rut for $data.

Any help? Thank you very much for the help
 
Well, all you've done is define a function called validaRut(), but nothing actually calls it.

You could add ...

PHP:
return valaRut($data);

... after the function, so you are actually calling it and returning the response. But it's risky deifing function in validations, as it's possible they might get run more than once. Could work round that by checking to see if the function exists ... but .. easiest thing to do is probably just strip the function(){...} part off, so it's just inline code.

I've assigned $data to $rut, so your code stayed the same. You could instead rename $rut to $data throughout. Makes no difference really.

PHP:
    $rut = $data;
    if(strpos($rut,"-")==false){
        $RUT[0] = substr($rut, 0, -1);
        $RUT[1] = substr($rut, -1);
    }else{
        $RUT = explode("-", trim($rut));
    }
    $elRut = str_replace(".", "", trim($RUT[0]));
    $factor = 2;
    for($i = strlen($elRut)-1; $i >= 0; $i--):
        $factor = $factor > 7 ? 2 : $factor;
        $suma += $elRut{$i}*$factor++;
    endfor;
    $resto = $suma % 11;
    $dv = 11 - $resto;
    if($dv == 11){
        $dv=0;
    }else if($dv == 10){
        $dv="k";
    }else{
        $dv=$dv;
    }
  if($dv == trim(strtolower($RUT[1]))){
      return true;
  }else{
      return false;
  }


-- hugh
 
We are in need of some funding.
More details.

Thank you.

Members online

No members online now.
Back
Top