Skip to content

Commit

Permalink
Valida cpf
Browse files Browse the repository at this point in the history
  • Loading branch information
matheuspdf committed May 21, 2024
1 parent fa8bdfd commit 378a145
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 5 deletions.
10 changes: 9 additions & 1 deletion eventex/subscriptions/forms.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,16 @@
from django import forms
from django.core.exceptions import ValidationError


def validate_cpf(value):
if not value.isdigit():
raise ValidationError('CPF deve conter apenas números.', 'digits')
if len(value) != 11:
raise ValidationError('CPF deve ter 11 números.', 'length')


class SubscriptionForm(forms.Form):
name = forms.CharField(label='Nome')
cpf = forms.CharField(label='CPF')
cpf = forms.CharField(label='CPF', validators=[validate_cpf])
email = forms.EmailField(label='E-mail')
phone = forms.CharField(label='Telefone')
36 changes: 32 additions & 4 deletions eventex/subscriptions/tests/test_form_subscription.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,38 @@


class SubscriptionFormTest(TestCase):
def setUp(self):
self.form = SubscriptionForm()

def test_form_has_fields(self):
"""Form must have 4 fields"""
form = SubscriptionForm()
expected = ['name', 'cpf', 'email', 'phone']
self.assertSequenceEqual(expected, list(self.form.fields))
self.assertSequenceEqual(expected, list(form.fields))

def test_cpf_is_digit(self):
"""CPF must only accept digits."""
form = self.make_validated_form(cpf='ABCD5678912')
self.assertFormErrorCode(form, 'cpf', 'digits')

def test_cpf_has_11_digits(self):
"""CPF must have 11 digits."""
form = self.make_validated_form(cpf='1234')
self.assertFormErrorCode(form, 'cpf', 'length')

def assertFormErrorCode(self, form, field, code):
errors = form.errors.as_data()
errors_list = errors[field]
exception = errors_list[0]
self.assertEqual(code, exception.code)

def assertFormErrorMessage(self, form, field, msg):
errors = form.errors
errors_list = errors[field]
self.assertListEqual([msg], errors_list)

def make_validated_form(self, **kwargs):
valid = dict(name='Matheus Lopes', cpf='12345678912',
email='[email protected]', phone='11984028729')

data = dict(valid, **kwargs)
form = SubscriptionForm(data)
form.is_valid()
return form

0 comments on commit 378a145

Please sign in to comment.