Validate Spanish NIFS given to persons
485836
public static function isValidPersonal(string $nif): bool
    {
        return self::isValidDni($nif) || self::isValidNie($nif) || self::isValidOtherPersonalNif($nif);
    }
839586
public static function validate($data) {
        if ( ! is_array($data) ) return '$data must be an array';
        $id = U::get($data, 'id');
        if ( $id ) {
            if ( ! is_int($id) ) return "id must be an an integer";
        }
        $uk1 = U::get($data, 'uk1');
        if ( $uk1 ) {
            if ( ! is_string($uk1) ) return "uk1 must be a string";
            if ( strlen($uk1) < 1 || strlen($uk1) > 150 ) return "uk1 must be no more than 150 characters";
        }
        $sk1 = U::get($data, 'sk1');
        if ( $sk1 ) {
            if ( ! is_string($sk1) ) return "sk1 must be a string";
            if ( strlen($sk1) < 1 || strlen($sk1) > 75 ) return "sk1 must be no more than 75 characters";
        }
        $tk1 = U::get($data, 'tk1');
        if ( $tk1 ) {
            if ( ! is_string($tk1) ) return "tk1 must be a string";
            if ( strlen($tk1) < 1 ) return "tk1 cannot be empty";
        }
        $co1 = U::get($data, 'co1');
        if ( $co1 ) {
            if ( ! is_string($co1) ) return "co1 must be a string";
            if ( strlen($co1) < 1 || strlen($co1) > 150 ) return "co1 must be no more than 150 characters";
        }
        $co2 = U::get($data, 'co2');
        if ( $co2 ) {
            if ( ! is_string($co2) ) return "co2 must be a string";
            if ( strlen($co2) < 1 || strlen($co2) > 150 ) return "co2 must be no more than 150 characters";
        }
        return true;
    }
699528
function _isArrayValidate (type) {
  return (value) => {
    if (!Array.isArray(value)) {
      throw new Error(`Debe ser un Array.`)
    }
    value.forEach(val => {
      if ((type.key === 'STRING') && !Sequelize.Validator.len(`${val}`, 0, type.options.length)) {
        throw new Error(`Cada elemento debe ser una cadena de texto con un máximo de ${type.options.length} caracteres.`)
      }
      if ((type.key === 'TEXT') && !Sequelize.Validator.len(`${val}`, 0, 2147483647)) {
        throw new Error(`Cada elemento debe ser una cadena de texto.`)
      }
      if ((type.key === 'INTEGER') && !Sequelize.Validator.isInt(`${val}`)) {
        throw new Error(`Cada elemento debe ser de un número de tipo INTEGER.`)
      }
      if ((type.key === 'FLOAT') && !Sequelize.Validator.isFloat(`${val}`)) {
        throw new Error(`Cada elemento debe ser de un número de tipo FLOAT.`)
      }
      if ((type.key === 'BOOLEAN') && !Sequelize.Validator.isBoolean(`${val}`)) {
        throw new Error(`Cada elemento debe ser de tipo boolean.`)
      }
      if ((type.key === 'DATE') && !Sequelize.Validator.isDate(`${val}`)) {
        throw new Error(`Cada elemento debe ser una fecha válida.`)
      }
      if ((type.key === 'DATEONLY') && !Sequelize.Validator.isDate(`${val}`)) {
        throw new Error(`Cada elemento debe ser una fecha válida.`)
      }
      if ((type.key === 'TIME') && !moment(val, 'HH:mm:ss', true).isValid()) {
        throw new Error(`Cada elemento debe ser una hora válida.`)
      }
      if ((type.key === 'JSON') && (typeof val !== 'object')) {
        throw new Error(`Cada elemento debe ser un objeto de tipo JSON.`)
      }
      if ((type.key === 'JSONB') && (typeof val !== 'object')) {
        throw new Error(`Cada elemento debe ser un objeto de tipo JSON.`)
      }
      if ((type.key === 'UUID') && !Sequelize.Validator.isUUID(`${val}`)) {
        throw new Error(`Cada elemento debe ser una cadena de texto de tipo UUID.`)
      }
      if ((type.key === 'ENUM') && !Sequelize.Validator.isIn(`${val}`, type.values)) {
        throw new Error(`Cada elemento debe ser uno de los siguientes valores: ${type.values.toString()}.`)
      }
    })
  }
}
550131
protected function ensureMessages() {
        $this->messages = array_merge([
            'controlDigitError' => Yii::t('yii', 'The letter don\'t correspond to the number.')
            , 'patternError' => Yii::t('yii', 'The valid format for NIF is 8 digits followed by a valid letter and for NIE a letter followed by 7 digits and an ending letter.')
                ], $this->messages);
        $this->message = $this->messages['patternError'];
    }
1263551
public function mfaTokenValidate($iUserId, $sSalt, $sToken, $sIp)
    {
        $oDb = Factory::service('Database');
        $oDb->where('user_id', $iUserId);
        $oDb->where('salt', $sSalt);
        $oDb->where('token', $sToken);

        $oToken  = $oDb->get(NAILS_DB_PREFIX . 'user_auth_two_factor_token')->row();
        $bReturn = true;

        if (!$oToken) {

            $this->setError(lang('auth_twofactor_token_invalid'));
            return false;

        } elseif (strtotime($oToken->expires) <= time()) {

            $this->setError(lang('auth_twofactor_token_expired'));
            $bReturn = false;

        } elseif ($oToken->ip != $sIp) {

            $this->setError(lang('auth_twofactor_token_bad_ip'));
            $bReturn = false;
        }

        //  Delete the token
        $this->mfaTokenDelete($oToken->id);

        return $bReturn;
    }
1173488
private function validateRequirements()
    {
        // enough options to proceed
        if(!$this->option('all')) {
            $enoughOptions = false;
            foreach ($this->defaultsOptions as $app => $nr) {
                if($this->option($app)) {
                    $enoughOptions = true;
                    break;
                }
            }

            if(!$enoughOptions) {
                $this->error('No options given! Write --all=1 to create dummy for all default apps, or write --{APP NAME}={NUMBER OF DUMMIES TO CREATE} to proceed!');
                return false;
            }
        }

        // Ensure there is at least one user
        if(!User::count()) {
            $this->error('No Users found. Create a user with "make:user {email} {password}" command to proceed!');
            return false;
        }

        // Ensure there is at least one langauge
        if(!Language::count()) {
            $this->error('No languages found. Create a langauge manually via Admin interface to proceed!');
            return false;
        }

        return true;
    }
1246089
protected function validateAlias()
    {
        $field = 'alias';
        $value = $this->getSubmitted($field);

        if (empty($value)) {
            $this->unsetSubmitted($field);
            return null;
        }

        $label = $this->translation->text('Alias');

        if (mb_strlen($value) > 255) {
            $this->setErrorLengthRange($field, $label, 0, 255);
            return false;
        }

        if (preg_match('/^[A-Za-z0-9_.-]+$/', $value) !== 1) {
            $this->setErrorInvalid($field, $label);
            return false;
        }

        $updating = $this->getUpdating();

        if (isset($updating['alias']) && $updating['alias'] === $value) {
            return true; // Do not check own alias on update
        }

        if ($this->alias->exists($value)) {
            $this->setErrorExists($field, $label);
            return false;
        }

        return true;
    }
120414
private static function validation()
    {
        $files = ['Validator', 'ValidationResult'];
        $folder = static::$root.'Validation'.'/';

        self::call($files, $folder);

        //Initiate the validation surface
        Validator::ini();
    }
325862
public function ValidateUserInput()
    {
        $bIsValid = parent::ValidateUserInput();
        $oMsgManager = TCMSMessageManager::GetInstance();
        $aRequiredFields = array('accountNr', 'accountOwner', 'bankNr', 'bankName');
        foreach ($aRequiredFields as $sRequiredField) {
            $sValue = (array_key_exists($sRequiredField, $this->aPaymentUserData)) ? ($this->aPaymentUserData[$sRequiredField]) : ('');
            $sValue = trim($sValue);
            if (empty($sValue)) {
                $oMsgManager->AddMessage(self::MSG_MANAGER_NAME.'-'.$sRequiredField, 'ERROR-USER-REQUIRED-FIELD-MISSING');
                $bIsValid = false;
            }
        }

        return $bIsValid;
    }
531983
protected function isValidFormat()
    {
        // Read sample data (first 2 KB will do)
        $data = fread($this->fileHandle, 2048);

        // Count delimiters in file
        $delimiterCount = substr_count($data, ';');
        if ($delimiterCount < 1) {
            return false;
        }

        // Analyze first line looking for ID; signature
        $lines = explode("\n", $data);
        if (substr($lines[0], 0, 4) != 'ID;P') {
            return false;
        }

        return true;
    }
451294
public function validateNumAssertions()
    {
        $encryptedAssertionNodes = $this->document->getElementsByTagName('EncryptedAssertion');
        $assertionNodes = $this->document->getElementsByTagName('Assertion');

        $valid = $assertionNodes->length + $encryptedAssertionNodes->length == 1;

        if ($this->encrypted) {
            $assertionNodes = $this->decryptedDocument->getElementsByTagName('Assertion');
            $valid = $valid && $assertionNodes->length == 1;
        }

        return $valid;
    }
28683
function i18n_value($val_key, $params = NULL){
        if(isset($this->i18nContent)){
            if(isset($this->i18nContent[$val_key])){
                $mensaje= $this->i18nContent[$val_key];
                
                //Analiza si se pasaron parametros y si se pasaron cambia los valores correspondientes
                if($params != NULL){
                    foreach ($params as $key => $valor) {
                        $mensaje= str_replace(":$key", $valor, $mensaje);
                    }
                }                
                return $mensaje;
            }
        }
        else{
            \Enola\Error::general_error('I18n Error', 'Not specified any I18n file to make it run the i18n function');
        }
    }
1241153
def verifica(ver_list, res_dict, difs):
    ""
    for k, v in ver_list.items():
        # normalizo a float para poder comparar numericamente:
        if isinstance(v, (Decimal, int, long)):
            v = float(v)
        if isinstance(res_dict.get(k), (Decimal, int, long)):
            res_dict[k] = float(res_dict[k])
        if isinstance(v, list):
            # verifico que ambas listas tengan la misma cantidad de elementos:
            if v and not k in res_dict and v:
                difs.append("falta tag %s: %s %s" % (k, repr(v), repr(res_dict.get(k))))
            elif len(res_dict.get(k, []))!=len(v or []):
                difs.append("tag %s len !=: %s %s" % (k, repr(v), repr(res_dict.get(k))))
            else:
                # ordeno las listas para poder compararlas si vienen mezcladas
                rl = sorted(res_dict.get(k, []))
                # comparo los elementos uno a uno:
                for i, vl in enumerate(sorted(v)):
                    verifica(vl, rl[i], difs)
        elif isinstance(v, dict):
            # comparo recursivamente los elementos:
            verifica(v, res_dict.get(k, {}), difs)
        elif res_dict.get(k) is None or v is None:
            # alguno de los dos es nulo, verifico si ambos lo son o faltan
            if v=="":
                v = None
            r = res_dict.get(k)
            if r=="":
                r = None
            if not (r is None and v is None):
                difs.append("%s: nil %s!=%s" % (k, repr(v), repr(r)))
        elif type(res_dict.get(k)) == type(v):
            # tipos iguales, los comparo directamente
            if res_dict.get(k) != v:
                difs.append("%s: %s!=%s" % (k, repr(v), repr(res_dict.get(k))))
        elif isinstance(v, float) or isinstance(res_dict.get(k), float):
            # comparar numericamente
            if float(res_dict.get(k)) != float(v):
                difs.append("%s: %s!=%s" % (k, repr(v), repr(res_dict.get(k))))
        elif unicode(res_dict.get(k)) != unicode(v):
            # tipos diferentes, comparo la representación  
            difs.append("%s: str %s!=%s" % (k, repr(v), repr(res_dict.get(k))))
        else:
            pass
41128
public static function validar($cnpj)
    {
        $cnpj = static::digitos($cnpj);

        if (strlen($cnpj) <> 14) {
            return false;
        }

        $regex = "/^0+$|^1+$|^2+$|^3+$|^4+$|^5+$|^6+$|^7+$|^8+$|^9+$/";
        if (preg_match($regex, $cnpj)) {
            return false;
        }

        // Primeiro dígito
        $multiplicadores = array (5, 4, 3, 2, 9, 8, 7, 6, 5, 4, 3, 2);
        $soma            = 0;
        for ($i = 0; $i <= 11; $i++) {
            $soma += $multiplicadores[$i] * $cnpj[$i];
        }
        $d1 = 11 - ($soma % 11);
        if ($d1 >= 10) {
            $d1 = 0;
        }

        // Segundo dígito
        $multiplicadores = array (6, 5, 4, 3, 2, 9, 8, 7, 6, 5, 4, 3, 2);
        $soma            = 0;
        for ($i = 0; $i <= 12; $i++) {
            $soma += $multiplicadores[$i] * $cnpj[$i];
        }
        $d2 = 11 - ($soma % 11);
        if ($d2 >= 10) {
            $d2 = 0;
        }

        return $d1 == $cnpj[12] && $d2 == $cnpj[13];
    }
879260
function validate($value, $key, $fields, $options, $exists, \CharlotteDunois\Validation\Validator $validator) {
        if(isset($_FILES[$key])) {
            if(!\file_exists($_FILES[$key]['tmp_name'])) {
                return 'formvalidator_make_invalid_file';
            }
            
            $size = \getimagesize($_FILES[$key]['tmp_name']);
        } else {
            if(!$exists) {
                return false;
            }
            
            $size = @\getimagesizefromstring($value);
        }
        
        if(!$size) {
            return 'formvalidator_make_invalid_file';
        }
        
        $n = \explode(',', $options);
        foreach($n as $x) {
            $k = \explode('=', $x);
            switch($k[0]) {
                case 'min_width': // @codeCoverageIgnore
                    if($k[1] > $size[0]) {
                        return array('formvalidator_make_min_width', array('{0}' => $options));
                    }
                break;
                case 'min_height': // @codeCoverageIgnore
                    if($k[1] > $size[1]) {
                        return array('formvalidator_make_min_height', array('{0}' => $options));
                    }
                break;
                case 'width': // @codeCoverageIgnore
                    if($k[1] != $size[0]) {
                        return array('formvalidator_make_width', array('{0}' => $options));
                    }
                break;
                case 'height': // @codeCoverageIgnore
                    if($k[1] != $size[1]) {
                        return array('formvalidator_make_height', array('{0}' => $options));
                    }
                break;
                case 'max_width': // @codeCoverageIgnore
                    if($k[1] < $size[0]) {
                        return array('formvalidator_make_max_width', array('{0}' => $options));
                    }
                break;
                case 'max_height': // @codeCoverageIgnore
                    if($k[1] < $size[1]) {
                        return array('formvalidator_make_max_height', array('{0}' => $options));
                    }
                break;
                case 'ratio': // @codeCoverageIgnore
                    if(\mb_strpos($k[1], '/') !== false) {
                        $k[1] = \explode('/', $k[1]);
                        $k[1] = $k[1][0] / $k[1][1];
                    }
                    
                    if(\number_format(($size[0] / $size[1]), 1) != \number_format($k[1], 1)) {
                        return array('formvalidator_make_ratio', array('{0}' => $options));
                    }
                break;
            }
        }
        
        return true;
    }
533681
function(n) {
				
				// Es un número válido, no empieza por 0X (ej: 02) y solo contiene números y puntuación
				
				return !isNaN(parseFloat(n)) && isFinite(n) && /^(?!0\d)/.test(n) && /^[\d\.]+$/.test(n);

			}
905815
private function validateNip(): bool
    {
        if (!\preg_match('/^[0-9]{10}$/', $this->value)) {
            $this->setError(self::VALIDATOR_ERROR_NIP_INCORRECT_FORMAT);
            return false;
        }

        $checksum = 0;
        $weightArray = [6, 5, 7, 2, 3, 4, 5, 6, 7];

        for ($i = 0; $i < 9; $i++) {
            $checksum += $weightArray[$i] * $this->value[$i];
        }
        $isValid = $checksum % 11 == $this->value[9] ? true : false;
        if (!$isValid) {
            $this->setError(self::VALIDATOR_ERROR_NIP_INVALID_NUMBER);
        }

        return $isValid;
    }