コード例 #1
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
コード例 #2
0
    def cpf_validator(cls, v):
        cpf = CPF()

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

        return v
コード例 #3
0
    def validate_cpf(form, field):
        from validate_docbr import CPF

        cpf = CPF()

        if not cpf.validate(field.data):
            raise ValidationError("CPF Invalido")
コード例 #4
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
コード例 #5
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()
コード例 #6
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")
コード例 #7
0
    def validate(self):
        cpf = CPF()

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

        return Result.ok()
コード例 #8
0
ファイル: views.py プロジェクト: Me-Adota/website
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
コード例 #9
0
 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
コード例 #10
0
ファイル: maskcpf.py プロジェクト: miguelzamberlan/pse
def maskcpf(value):

    cpf = CPF()

    cpfmascarado = cpf.mask(str(value))

    return str(cpfmascarado)
コード例 #11
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))
コード例 #12
0
ファイル: validators.py プロジェクト: lhggomes/API-Django
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)
コード例 #13
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
コード例 #14
0
    def valida(self, documento):

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

        else:
            raise ValueError('Quantdades dígitos inválidos')
コード例 #15
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
コード例 #16
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')
コード例 #17
0
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})
コード例 #18
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)
コード例 #19
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'
            },
        )
コード例 #20
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()
コード例 #21
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_
コード例 #22
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)
コード例 #23
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
コード例 #24
0
    def __extra_attribs(self, dictio_):
        cpf_validator = CPF()
        dictio_.update({
            'area':
            dictio_['vaccination_site'].split('-', 1)[0].strip(),
            'vaccination_site':
            dictio_['vaccination_site'].split('-', 1)[1].strip(),
            'cpf':
            self.__formatCPF(dictio_['cpf'].replace('\'', '')),
            'valid_cpf':
            cpf_validator.validate(dictio_['cpf'].replace('\'', ''))
        })

        return dictio_
コード例 #25
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
コード例 #26
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
コード例 #27
0
def validate_cpf(value):

    if not CPF().validate(value):
        raise ValidationError(
            _('CPF %(value)s inválido'),
            params={'value': value},
        )
コード例 #28
0
ファイル: views.py プロジェクト: miguelzamberlan/pse
def ficha_inscricao(request, id):

    cpf = CPF()

    dados = get_object_or_404(Inscricao, pk=id)

    cpfcandidato = cpf.mask(str(dados.cpfcandidato))
    cpfresponsavel = cpf.mask(str(dados.cpfresponsavel))

    dados.cpfresponsavel = cpfresponsavel
    dados.cpfcandidato = cpfcandidato

    return render(request, 'ficha_inscricao.html', {
        'codinscricao': id,
        'dados': dados,
    })
コード例 #29
0
def procura_cpf(text: str) -> list:
    '''
    Retorna uma lista com CPFs encontrados, somente com números.
    :param text: str
    :return: list
    '''
    regexCPF = re.compile(r'\b\d{11,11}\b|\b\d\d\d.\d\d\d.\d\d\d-\d\d\b')
    cpfs = set([
        ''.join([num for num in x if num.isalnum()])
        for x in regexCPF.findall(text)
    ])
    valid_cpfs = []
    for cpf in cpfs:
        cpf_num = CPF()
        if cpf_num.validate(cpf):
            valid_cpfs.append(cpf)
    return valid_cpfs
コード例 #30
0
def create_user():
    cpf = CPF()

    data = request.get_json()

    if not all(x.isalpha() or x.isspace() for x in str(data['name'])) or len(
            str(data['name'])) < 3 or len(str(data['name'])) > 100:
        return jsonify({'message': 'Nome inválido!'}), 400
    elif not cpf.validate(str(data['cpf'])):
        return jsonify({'message': 'CPF inválido!'}), 400
    elif datetime.date.today().year - datetime.datetime.strptime(
            str(data['birthdate']), "%d/%m/%Y").year < 18:
        return jsonify({'message': 'Usuário menor de idade!'}), 400
    elif str(data['gender']) != "M" and str(data['gender']) != "F":
        return jsonify({'message': 'Gênero inválido!'}), 400
    elif not str(data['phone']).isdigit() or len(str(data['phone'])) < 10:
        return jsonify({'message': 'Telefone inválido!'}), 400
    elif not validate_email(str(data['email'])):
        return jsonify({'message': 'Email inválido!'}), 400
    elif len(str(data['password'])) < 8 or len(str(data['password'])) > 20:
        return jsonify({'message': 'Senha inválida!'}), 400

    prospect_cpf = User.query.filter_by(cpf=data['cpf']).first()
    prospect_email = User.query.filter_by(email=data['email']).first()

    if prospect_cpf:
        return jsonify({'message': 'CPF já cadastrado!'}), 400
    elif prospect_email:
        return jsonify({'message': 'Email já cadastrado!'}), 400

    hashed_password = generate_password_hash(data['password'], method='sha256')
    new_user = User(public_id=str(uuid.uuid4()),
                    name=data['name'],
                    cpf=data['cpf'],
                    birthdate=data['birthdate'],
                    gender=data['gender'],
                    phone=data['phone'],
                    email=data['email'],
                    password=hashed_password,
                    passwordResetToken=None,
                    passwordResetExpires=None)
    db.session.add(new_user)
    db.session.commit()

    return jsonify({'message': 'Usuário cadastrado com sucesso!'}), 200