Validate Brazilian CPF

@author rafael-neri (modified)
@link https://gist.github.com/rafael-neri/ab3e58803a08cb4def059fce4e3c0e40

@param string $cpf Up to 11 digits, anything else is discarded

@return string validated (only numbers) or false if invalid
175222
public static function cpf($cpf)
    {
        // Extract numbers
        $cpf = preg_replace('/[^\d]/', '', $cpf);

        // Check amount of numbers
        if (strlen($cpf) > 11) {
            return false;
        }
        $cpf = str_pad($cpf, 11, '0', STR_PAD_LEFT);

        // Check for same digit sequence
        if (preg_match('/(\d)\1{10}/', $cpf)) {
            return false;
        }

        // Calculate check digits
        for ($t = 9; $t < 11; $t++) {
            for ($d = 0, $c = 0; $c < $t; $c++) {
                $d += $cpf{$c} * (($t + 1) - $c);
            }
            $d = ((10 * $d) % 11) % 10;
            if ($cpf{$c} != $d) {
                return false;
            }
        }

        return $cpf;
    }
1362158
function calcDigits(cpf)
{
    cpf = cpf.reverse();

    var v1 = 0;
    var v2 = 0;

    for (var i = 0; i < 9; i++) {
        v1 = v1 + cpf[i] * (9 - (i % 10));
        v2 = v2 + cpf[i] * (9 - ((i + 1) % 10));
    }

    v1 = (v1 % 11) % 10;
    v2 = ((v2 + v1 * 9) % 11) % 10;

    return v1 + '' + v2;
}
757578
private function validateIENew(string $vatNumber): bool
    {
        $checksum = strtoupper(substr($vatNumber, 7, 1));
        $checkNumber = substr($vatNumber, 0, 8);
        $checkval = 0;

        for ($i = 2; $i <= 8; $i++) {
            $checkval += (int)$checkNumber[8 - $i] * $i;
        }

        if (strlen($vatNumber) == 9) {
            $checkval += (9 * strpos($this->alphabet, $vatNumber[8]));
        }

        $checkval = ($checkval % 23);

        if ($checkval == 0) {
            return $checksum == 'W';
        }

        $checkchar = 'A';
        for ($i = $checkval - 1; $i > 0; $i--) {
            $checkchar++;
        }

        return $checkchar == $checksum;
    }
801741
public function validate($value) {
        if(!is_numeric($value)) {
            throw new DataType('value', 'number', $value);
        }
        
        if($value > $this->max) {
            return new ValidationResult(false, sprintf('Value has to be below %d', $this->max));
        }
        
        return new ValidationResult(true);
    }
733133
public function validate($code): bool
    {
        $codeLength = strlen($code);

        return ctype_digit($code) && $codeLength == $this->config['total_digits'] && strlen($code) <= 6;
    }
565011
public static function validate($vat)
    {
        if (empty($vat) || null === $vat || '' === $vat) {
            return false;
        }

        $countryCode = substr($vat, 0, 2);
        if (false === self::isValidCountryCode($countryCode)) {
            return false;
        }

        $vat = substr($vat, 2);
        if (0 === preg_match('/^'.self::$patterns[$countryCode].'$/', $vat)) {
            return false;
        }

        return true;
    }
511265
public function validateNumeric()
    {
        $val = $this->getValue() + 0;

        return $val >= $this->getArg(0) && $val <= $this->getArg(1);
    }
884029
public static function validate($cif)
    {
        $cifCodes = 'JABCDEFGHI';

        if (9 !== strlen($cif)) {
            return false;
        }
        $cif = strtoupper(trim($cif));
        $sum = (string) Nif::getCifSum($cif);

        $n = (10 - substr($sum, -1)) % 10;

        if (preg_match('/^[ABCDEFGHJKNPQRSUVW]{1}/', $cif)) {
            if (in_array($cif[0], array('A', 'B', 'E', 'H'))) {
                // Numerico
                return $cif[8] == $n;
            } elseif (in_array($cif[0], array('K', 'P', 'Q', 'S'))) {
                // Letras
                return $cif[8] == $cifCodes[$n];
            } else {
                // Alfanumérico
                if (is_numeric($cif[8])) {
                    return $cif[8] == $n;
                } else {
                    return $cif[8] == $cifCodes[$n];
                }
            }
        }

        return false;
    }
1342034
private function utf8_chr($cp) {

        if (!is_int($cp)) {
            exit("$cp is not integer\n");
        }

        // UTF-8 prohibits characters between U+D800 and U+DFFF
        // https://tools.ietf.org/html/rfc3629#section-3
        //
        // Q: Are there any 16-bit values that are invalid?
        // http://unicode.org/faq/utf_bom.html#utf16-7

        if ($cp < 0 || (0xD7FF < $cp && $cp < 0xE000) || 0x10FFFF < $cp) {
            exit("$cp is out of range\n");
        }

        if ($cp < 0x10000) {
            return json_decode('"\u'.bin2hex(pack('n', $cp)).'"');
        }

        // Q: Isn’t there a simpler way to do this?
        // http://unicode.org/faq/utf_bom.html#utf16-4
        $lead = 0xD800 - (0x10000 >> 10) + ($cp >> 10);
        $trail = 0xDC00 + ($cp & 0x3FF);

        return json_decode('"\u'.bin2hex(pack('n', $lead)).'\u'.bin2hex(pack('n', $trail)).'"');
    }
464012
public function isValid($value)
    {
        if (!is_string($value) && !is_int($value) && !is_float($value)) {
            $this->_error(self::INVALID);
            return false;
        }

        if (is_int($value)) {
            return true;
        }

        $this->_setValue($value);
        if ($this->_locale === null) {
            $locale        = localeconv();
            $valueFiltered = str_replace($locale['decimal_point'], '.', $value);
            $valueFiltered = str_replace($locale['thousands_sep'], '', $valueFiltered);

            if (strval(intval($valueFiltered)) != $valueFiltered) {
                $this->_error(self::NOT_INT);
                return false;
            }

        } else {
            try {
                if (!Zend_Locale_Format::isInteger($value, array('locale' => $this->_locale))) {
                    $this->_error(self::NOT_INT);
                    return false;
                }
            } catch (Zend_Locale_Exception $e) {
                $this->_error(self::NOT_INT);
                return false;
            }
        }

        return true;
    }
374306
public static function validateKey ($key)
    {
        $hash = substr($key, 0, 2);
        $encrypted = substr($key, 2);
        if ($hash != substr(md5(Pluf::f('secret_key') . $encrypted), 0, 2)) {
            throw new Pluf_Form_Invalid(
                    __(
                            'The validation key is not valid. Please copy/paste it from your confirmation email.'));
        }
        $cr = new Pluf_Crypt(md5(Pluf::f('secret_key')));
        return explode(':', $cr->decrypt($encrypted), 3);
    }
619193
public function validate($value)
    {
        $options = array('options' => array(
            'max_range' => $this->max,
            'min_range' => $this->min
        ));

        return empty($value) || (false !== filter_var($value, FILTER_VALIDATE_INT, $options));
    }
734614
public function validate($input)
    {
        /**
         * Validation criteria:
         * - 8 or 9 digits (only numbers!)
         * - Be able to pass the '11 test'
         * - Musn't contain any information.
         *   Cannot implement at this stage, not clear enough defined! Is 1337 information?
         * - Can not be sequential (nummeric)
         * - Is not 900000000 through 999999999 (test numbers)
         *
         * Based on public information: http://nl.wikipedia.org/wiki/Burgerservicenummer
         */

        // Validate: 8 or 9 digits (only numbers!)
        if (strlen($input) < 8 || strlen($input) > 9) {
            return false;
        }

        // Check if they are actually numbers
        // Alternatively, use ctype_digit($input) !
        if (preg_match('/[^0-9]/', $input)) {
            return false;
        }

        // See if the number passes the Eleventest (http://nl.wikipedia.org/wiki/Elfproef)
        if ($this->elevenTest($input)) {
            return false;
        }

        // Check if the numbers are sequential
        // Will not match when sequential numbers are used
        if (preg_match('/\d{5}/u', $input)) {
            return false;
        }

        // Validate if the number is not in the test range!
        return filter_var(
            $input,
            FILTER_VALIDATE_INT,
            array('options' => array('min_range' => '900000000', 'max_range' => '999999999'))
        );
    }
780355
public function isValid($value)
    {
        $value = strtoupper($value);
        $this->_setValue($value);

        if (empty($this->_locale)) {
            $region = substr($value, 0, 2);
        } else {
            $region = new Zend_Locale($this->_locale);
            $region = $region->getRegion();
        }

        if (!array_key_exists($region, $this->_ibanregex)) {
            $this->_setValue($region);
            $this->_error(self::NOTSUPPORTED);
            return false;
        }

        if (!preg_match($this->_ibanregex[$region], $value)) {
            $this->_error(self::FALSEFORMAT);
            return false;
        }

        $format = substr($value, 4) . substr($value, 0, 4);
        $format = str_replace(
            array('A',  'B',  'C',  'D',  'E',  'F',  'G',  'H',  'I',  'J',  'K',  'L',  'M',
                  'N',  'O',  'P',  'Q',  'R',  'S',  'T',  'U',  'V',  'W',  'X',  'Y',  'Z'),
            array('10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22',
                  '23', '24', '25', '26', '27', '28', '29', '30', '31', '32', '33', '34', '35'),
            $format);

        $temp = intval(substr($format, 0, 1));
        $len  = strlen($format);
        for ($x = 1; $x < $len; ++$x) {
            $temp *= 10;
            $temp += intval(substr($format, $x, 1));
            $temp %= 97;
        }

        if ($temp != 1) {
            $this->_error(self::CHECKFAILED);
            return false;
        }

        return true;
    }
638782
public User existsByCpf(String cpf) {
		Criteria criteria = this.dao.newCriteria(User.class).add(Restrictions.eq("cpf", cpf));
		return (User) criteria.uniqueResult();
	}
358113
public function validate($input)
    {
        $checkDigit = explode(',', '0,1,2,3,4,5,6,7,8,9,a,b,c,d,e,f,h,j,k,l,m,n,p,r,s,t,u,v,w,x,y');

        // Get the check digit
        $check = strtolower(substr($input, -1, 1));

        // Remove dash, plus or A
        if (strlen($input) == 11) {
            $input = substr($input, 0, 6) . substr($input, 7, 3);
        } else {
            $input = substr($input, 0, 9);
        }

        if (!preg_match('/^\d+$/', $input)) {
            return false;
        }

        // Do the math
        $result = $input % 31;

        return $checkDigit[$result] == $check;
    }
890305
public function isValid($value)
    {
        if (!is_string($value) && !is_int($value) && !is_float($value)) {
            $this->error(self::INVALID);

            return false;
        }

        $value = trim((string) $value);
        $this->value = $value;
        /** @var array $parts */
        $parts = explode('.', $value);

        if (count($parts) > 2) {
            $this->error(self::INVALID);

            return false;
        }

        foreach ($parts as $number) {
            // Check if number is a valid integer
            if (false !== filter_var($number, FILTER_VALIDATE_INT)) {
                continue;
            }

            // Check if number is invalid because of integer overflow
            $invalid = array_filter(
                str_split($number, strlen((string) PHP_INT_MAX) - 1),
                function($chunk) {
                    // Leading zeros should not invalidate the chunk
                    $chunk = ltrim($chunk, '0');

                    // Allow chunks containing zeros only
                    return '' !== $chunk && false === filter_var($chunk, FILTER_VALIDATE_INT);
                }
            );

            if (count($invalid) !== 0) {
                $this->error(self::INVALID);

                return false;
            }
        }

        return true;
    }