validate fields with only letters

validate fields with only letters

rrzavaletarrzavaleta Posts: 78Questions: 52Answers: 2
edited March 2015 in Editor

Hi I need to validate fields in the editor that only allow letters , I tried something like this

public static function sololetras ( $val, $data, $opts, $host ) {
        $cfg = Validate::_extend( $opts, null, array(
            'message' => "Este campo solo permite letras"
        ) );

        $common = Validate::_common( $val, $cfg );
        if ( $common !== null ) {
            return $common;
        }
        return ! ereg('[^A-Za-z]', $val ) ?
            $cfg['message'] :
            true;
            
    }

but without results , I hope can help

Answers

  • allanallan Posts: 63,498Questions: 1Answers: 10,471 Site admin

    Aside from ereg being deprecated in PHP 5.3 ( http://php.net/manual/en/function.ereg.php ) that looks like it should work. Have you added debugging code to it to see where it is going wrong?

    Allan

  • rrzavaletarrzavaleta Posts: 78Questions: 52Answers: 2
    edited March 2015

    Hi allan , I just want to share how you can validate fields to allow only letters .
    Perhaps there is another way , but this is how I fixed.

    In the file add the following function Validate.php

    public static function sololetras ( $val, $data, $opts, $host ) {
            $cfg = Validate::_extend( $opts, null, array(
                'message' => "Este campo solo permite letras"
            ) );
            
    
            $common = Validate::_common( $val, $cfg );
            if ( $common !== null  ) {
                return $common;
            }
            
            if( is_numeric ($val ))
                {
                return $cfg['message'];
                }
                else {
                $permitidos = "abcdefghijklmnñopqrstuvwxyzABCDEFGHIJKLMNÑOPQRSTUVWXYZ ";
                  for ($i=0; $i<strlen($val); $i++){    
          if (strpos($permitidos, substr($val,$i,1))===false){
                    return $cfg['message'];
          }
       }
        
                return true;
                }
    
            
        }
    
  • allanallan Posts: 63,498Questions: 1Answers: 10,471 Site admin

    Thanks for sharing your solution! Using a regular expression would probably be more efficient, but if it works, then that is great!

    Allan

This discussion has been closed.