Exemplo n.º 1
0
def maskcpf(value):

    cpf = CPF()

    cpfmascarado = cpf.mask(str(value))

    return str(cpfmascarado)
Exemplo n.º 2
0
    def validate(self):
        cpf = CPF()

        if not cpf.validate(self.cpf):
            return Result.fail('CPF %s inválido!' % self.cpf)

        return Result.ok()
Exemplo n.º 3
0
    def validate_cpf(form, field):
        from validate_docbr import CPF

        cpf = CPF()

        if not cpf.validate(field.data):
            raise ValidationError("CPF Invalido")
Exemplo n.º 4
0
    def cpf_validator(cls, v):
        cpf = CPF()

        if not cpf.validate(v):
            raise ValueError('Invalid CPF')

        return v
 def __validate_social_security_number(social_security_number: str) -> bool:
     logging.debug("Validating phone")
     cpf = CPF()
     valid_social_security_number = cpf.validate(doc=social_security_number)
     logging.debug(
         f"Valid social_security_number: {valid_social_security_number}")
     return valid_social_security_number
Exemplo n.º 6
0
def valida_documento(value):
    '''
        Valida CPF e CNPJ dependendo do tamanho do documento passado.
    '''
    if len(value) == 11:
        cpf = CPF()
        try:
            assert cpf.validate(value)
        except AssertionError:
            raise ValidationError(
                {
                    'erro': 'Documento inválido!'
                }
            )
    elif len(value) == 14:
        cnpj = CNPJ()
        try:
            assert cnpj.validate(value)
        except AssertionError:
            raise ValidationError(
                {
                    'erro': 'Documento inválido!'
                }
            )
    else:
        raise ValidationError(
            {
                'erro': 'Documento inválido!'
            }
        )

    return value
Exemplo n.º 7
0
def criando_pessoas(quantidade_de_pessoas):
    fake = Faker('pt-BR')
    Faker.seed(10)
    for _ in range(quantidade_de_pessoas):
        cpf = CPF()
        nome = fake.name()
        email = '{}@{}'.format(nome.lower(), fake.free_email_domain())
        email = email.replace(' ', '')
        cpf = cpf.generate()
        rg = "{}{}{}{}".format(random.randrange(10, 99),
                               random.randrange(100, 999),
                               random.randrange(100, 999),
                               random.randrange(0, 9))
        celular = "{} 9{}-{}".format(
            random.randrange(10, 21),
            random.randrange(4000, 9999),
            random.randrange(4000, 9999),
        )
        ativo = random.choice([True, False])
        p = Cliente(nome=nome,
                    email=email,
                    cpf=cpf,
                    rg=rg,
                    celular=celular,
                    ativo=ativo)
        p.save()
Exemplo n.º 8
0
    def validate_cpf(self, value: str) -> str:
        cpf_validator = CPF()
        cpf = value

        if not cpf_validator.validate(cpf):
            raise serializers.ValidationError("Invalid CPF.")
        return cpf
Exemplo n.º 9
0
 def clean_cpf(self):
     cpf = self.cleaned_data.get("cpf", "").strip()
     cpf_validator = CPF()
     if cpf_validator.validate(cpf):
         return cpf
     else:
         raise ValidationError("CPF Inválido")
Exemplo n.º 10
0
def validate_fields(data, errors):
    errors['has_errors'] = 0
    errors['error'] = {}
    index = 0

    if ('cpf' in data and data['cpf'] != ''):
        cpf = CPF()
        cpf_valid = cpf.validate(data['cpf'])
        if (cpf_valid == False):
            errors['has_errors'] = 1
            errors['error'].update({
                index:
                'CPF não válido por favor verifique novamente, ou deixe o campo em branco'
            })
            index += 1

    if ('mobile_phone' in data and data['mobile_phone'] != ''):
        if (len(data['mobile_phone']) < 15):
            errors['has_errors'] = 1
            errors['error'].update({
                index:
                'Numero de telefone não válido por favor verifique novamente, ou deixe o campo em branco'
            })
            index += 1
    return errors
Exemplo n.º 11
0
    def post(self):
        args = parser.parse_args()
        cnpj = args['estabelecimento']
        cpf = args['cliente']
        value = args['valor']
        description = args['descricao']

        if not CPF().validate(cpf) or not CNPJ().validate(cnpj):
            return {'aceito': False}, 202

        cnpj = extract_numbers(cnpj)
        cpf = extract_numbers(cpf)

        store = Store.query.filter_by(cnpj=cnpj).first()
        if not store:
            store = Store(cnpj=cnpj)
            db.session.add(store)

        client = Client.query.filter_by(cpf=cpf).first()
        if not client:
            client = Client(cpf=cpf)
            db.session.add(client)

        transaction = Transaction(value=value, description=description)
        transaction.store = store
        transaction.client = client

        db.session.add(transaction)
        db.session.commit()

        return {'aceito': True}, 201
Exemplo n.º 12
0
def validate_cpf(value):

    if not CPF().validate(value):
        raise ValidationError(
            _('CPF %(value)s inválido'),
            params={'value': value},
        )
Exemplo n.º 13
0
    def valida(self, documento):

        if len(documento) == 11:
            validador = CPF()
            return validador.validate(documento)

        else:
            raise ValueError('Quantdades dígitos inválidos')
Exemplo n.º 14
0
def cpf_valid(cpf):
    """
    Return if the CPF is valid or not
    :param cpf: cpf in a string
    :return: True or False
    """
    cpf_validator = CPF()
    return cpf_validator.validate(cpf)
Exemplo n.º 15
0
 def clean_cpf(self):
     cpf_digitado = self.cleaned_data.get("cpf")
     cpf_validador = CPF()
     if not cpf_validador.validate(cpf_digitado):
         raise forms.ValidationError("O CPF informado não é válido!")
     # Estamos passando somente o only_digits porque zica se utilizarmos o cpf_validator com
     # os caracters não dígitos. Exemplo: . e -
     return cpf_validador.mask(cpf_validador._only_digits(cpf_digitado))
Exemplo n.º 16
0
    def clean_cpf(self):
        cpf = self.cleaned_data.get('cpf')

        validate_cpf = CPF()
        if not validate_cpf.validate(cpf):
            raise forms.ValidationError('O CPF é invalido')

        return cpf
Exemplo n.º 17
0
 def validate_cpf(self, value):
     cpf = CPF()
     if not bool(re.compile("^[ 0-9]+$").match(value)):
         raise serializers.ValidationError("Only numbers of cpf is allowed")
     if not cpf.validate(value):
         raise serializers.ValidationError("This cpf is invalid")
     if Salesman.objects.filter(cpf=value).exists():
         raise serializers.ValidationError("This cpf is already registered")
     return value
Exemplo n.º 18
0
def validate_cpf(value):
    if not value.isdigit():
        raise ValidationError('CPF deve conter apenas dígitos.', code='digits')

    if len(value) != 11:
        raise ValidationError('CPF deve conter 11 números.', code='len')

    cpf = CPF()
    if not cpf.validate(str(value)):
        raise ValidationError('CPF inválido', code='lógica')
Exemplo n.º 19
0
def driver_properly_configured(driver):
    valid_cpf = CPF().validate(driver.cpf)

    if not valid_cpf:
        raise serializers.ValidationError(_('CPF must be valid.'))

    valid_cnh = CNH().validate(driver.cnh)

    if not valid_cnh:
        raise serializers.ValidationError(_('CNH must be valid.'))
Exemplo n.º 20
0
def add_routes(api: Api) -> Api:
    api.add_resource(StudentController,
                     f"{PATH['BASE_PATH']}{PATH['STUDENTS']}",
                     resource_class_kwargs={
                         "student_service":
                         StudentService(person_repository=PersonRepository,
                                        student_repository=StudentRepository,
                                        person_translator=PersonTranslator,
                                        student_logger=Logger(
                                            StudentService.__name__)),
                         "student_validator":
                         StudentValidator(document_validator=DocumentValidator(
                             cpf_validator=CPF(),
                             cnpj_validator=CNPJ(),
                         ),
                                          string_validator=StringValidator,
                                          int_validator=IntValidator,
                                          float_validator=FloatValidator)
                     })

    api.add_resource(
        StudentControllerById,
        f"{PATH['BASE_PATH']}{PATH['STUDENTS']}{PARAM['STUDENT_ID']}",
        resource_class_kwargs={
            'student_validator':
            StudentValidator(document_validator=DocumentValidator(
                cpf_validator=CPF(),
                cnpj_validator=CNPJ(),
            ),
                             string_validator=StringValidator,
                             int_validator=IntValidator,
                             float_validator=FloatValidator),
            'student_service':
            StudentService(student_repository=StudentRepository(
                Logger(StudentRepository.__name__)),
                           student_logger=Logger(StudentService.__name__),
                           person_repository=PersonRepository,
                           person_translator=PersonTranslator),
            'student_logger':
            Logger(StudentControllerById.__name__)
        })
    return api
Exemplo n.º 21
0
 def clean(self):
     cpf = CPF()
     super().clean()
     dic_erros = {}
     if self.dataNascimento >= datetime.now().date():
         dic_erros['dataNascimento'] = ValidationError(
             'Data de Nascimento inválida')
     if not cpf.validate(self.cpf):
         dic_erros['cpf'] = ValidationError('Número de CPF inválido')
     if dic_erros:
         raise ValidationError(dic_erros)
Exemplo n.º 22
0
def validate_cpf(value):
    value = clean_special_characters(value)
    doc = CPF()
    if doc.validate(value):
        raise ValidationError(
            _('%(value)s is not an %(doc_type) valid'),
            params={
                'value': value,
                'doc_type': 'CPF'
            },
        )
def validate_cpf(value):
    cpf = CPF()

    try:
        valid = cpf.validate(value)
    except:
        valid = False

    if not valid:
        raise ValidationError(_("%(value)s is not a valid CPF"),
                              params={"value": value})
Exemplo n.º 24
0
def criando_alunos(quantidade_de_pessoas):
    fake = Faker('pt_BR')
    Faker.seed(10)
    for _ in range(quantidade_de_pessoas):
        cpf = CPF()
        nome = fake.name()
        rg = "{}{}{}{}".format(random.randrange(10, 99),random.randrange(100, 999),random.randrange(100, 999),random.randrange(0, 9) ) 
        cpf = cpf.generate()
        data_nascimento = fake.date_between(start_date='-18y', end_date='today')
        a = Aluno(nome=nome,rg=rg, cpf=cpf,data_nascimento=data_nascimento)
        a.save()
Exemplo n.º 25
0
    def clean(self):
        valid_cpf = CPF().validate(self.cpf)
        if not valid_cpf:
            raise ValidationError({
                'cpf': ValidationError(_('Invalid CPF %s.') % self.cpf, code='invalid'),
            })

        valid_cnh = CNH().validate(self.cnh)
        if not valid_cnh:
            raise ValidationError({
                'cnh': ValidationError(_('Invalid CNH %s.') % self.cnh, code='invalid'),
            })
Exemplo n.º 26
0
def treat_login(login):
    """ Checks if the login is a valid cpf

    Args:
        login (str): siga login

    Returns:
        str: cpf digits
    """
    if (not CPF().validate(login)):
        return ""
    return login.replace(".", "").replace("-", "")
Exemplo n.º 27
0
def cpf_validar(cpf) -> bool:

    if not cpf:
        return False

    numero = [int(digit) for digit in cpf if digit.isdigit()]

    if len(numero) != 11 or len(set(numero)) == 1:
        return False

    valida = CPF()

    return valida.validate(cpf)
Exemplo n.º 28
0
    def validate_cpf(self, key, value: Union[str, Tuple]):

        cpf = CPF()

        if type(value) is tuple:
            value = value[0]

        if not cpf.validate(value):
            exception = ValidationError()
            exception.errors = dict(cpf='Please try again with a valid CPF')
            raise exception

        return value
Exemplo n.º 29
0
    def __extra_attribs(self, dictio_):
        cpf_validator = CPF()

        dictio_.update(
            {
                'area': self.__get_area_by_vaccination_site(dictio_['vaccination_site']),
                'vaccination_site': self.__get_vaccination_site_name(dictio_['vaccination_site']),
                'cpf': self.__format_cpf(dictio_['cpf'].replace('\'', '')),
                'valid_cpf': cpf_validator.validate(dictio_['cpf'].replace('\'', ''))
            }
        )

        return dictio_
Exemplo n.º 30
0
    def check_doc(doc):
        client_doc = str(doc)
        client_doc_size = len(client_doc)

        if client_doc_size == 11:
            cpf = CPF()
            return cpf.validate(doc)

        elif client_doc_size == 14:
            cnpj = CNPJ()
            return cnpj.validate(doc)

        else:
            return False