Skip to content

Commit a0d4dbc

Browse files
committed
first commit
0 parents  commit a0d4dbc

16 files changed

+686
-0
lines changed

.gitignore

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
dist/
2+
comopublicar.txt
3+
multiform_validator.egg-info
4+
__pycache__

LICENSE

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
Copyright (c) 2023 The Python Packaging Authority
2+
3+
Permission is hereby granted, free of charge, to any person obtaining a copy
4+
of this software and associated documentation files (the "Software"), to deal
5+
in the Software without restriction, including without limitation the rights
6+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
7+
copies of the Software, and to permit persons to whom the Software is
8+
furnished to do so, subject to the following conditions:
9+
10+
The above copyright notice and this permission notice shall be included in all
11+
copies or substantial portions of the Software.
12+
13+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
18+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
19+
SOFTWARE.

README.md

Lines changed: 173 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,173 @@
1+
# Multiform-validator
2+
3+
[![PyPI version](https://badge.fury.io/py/multiform-validator.svg)](https://badge.fury.io/py/multiform-validator)
4+
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
5+
[![PyPI downloads](https://img.shields.io/pypi/dm/multiform-validator.svg?style=flat-square)](https://pypistats.org/packages/multiform-validator)
6+
7+
This package provides Python functions to validate various forms fields.
8+
9+
Documentation: https://multiform-validator.vercel.app/documentation/py
10+
11+
Feel free to find bugs and report them to me. Your feedback is highly appreciated. Hugs from Gabriel Logan!
12+
13+
If you want to help me, you can buy me a coffee (:
14+
15+
<p align="center">
16+
<a href="https://www.buymeacoffee.com/gabriellogan" target="_blank">
17+
<img src="https://cdn.buymeacoffee.com/buttons/v2/default-yellow.png" alt="Buy Me A Coffee" style="height: 50px !important;width: 180px !important;" >
18+
</a>
19+
</p>
20+
21+
### Installation
22+
23+
```bash
24+
pip install multiform-validator
25+
```
26+
27+
# Data Validator
28+
29+
This package contains various modules for validating different types of data. Below are the available validation modules:
30+
31+
# Avaliable for while
32+
33+
- **cnpjValidator**: CNPJ validation.
34+
- **cpfValidator**: CPF validation.
35+
- **getOnlyEmail**: Extracts only the email or emails address from a string.
36+
- **identifyFlagCard**: Identifies the flag of a credit card.
37+
- **isCreditCardValid**: Credit card validation.
38+
- **isEmail**: Email address validation format.
39+
- **passwordStrengthTester**: Password strength test.
40+
- **validateBRPhoneNumber**: Brazilian phone number validation.
41+
- **isValidImage**: Image validation.
42+
43+
## Usage
44+
45+
Here is an example of how to use the functions in this package:
46+
47+
```python
48+
from multiform_validator import (
49+
cnpjIsValid,
50+
cpfIsValid,
51+
getOnlyEmail,
52+
identifyFlagCard,
53+
isCreditCardValid,
54+
isEmail,
55+
passwordStrengthTester,
56+
validateBRPhoneNumber,
57+
isValidImage
58+
)
59+
```
60+
61+
### Usage Example
62+
63+
```python
64+
65+
print("Is email", isEmail("[email protected]")) # True
66+
print("Get only email", getOnlyEmail("awdawd wadawd wda awd [email protected] awdawdawd")) # [email protected]
67+
print("Password strength", passwordStrengthTester("aA1!asd@qd2asd")) # Strong
68+
print("Is CPF valid", cpfIsValid("123.456.789-02")['isValid']) # False
69+
print("Is CNPJ valid", cnpjIsValid("12.345.678/0001-09")) # { 'isValid': False, 'errorMsg': 'CNPJ is not valid' }
70+
print("Is credit card valid", isCreditCardValid("5117 2161 1334 8362")) # True
71+
print("Identify flag card", identifyFlagCard("5117 2161 1334 8362")) # Mastercard
72+
print("Validate BR phone number", validateBRPhoneNumber("(11) 91234-5678")) # { 'isValid': True, 'errorMsg': None }
73+
74+
```
75+
76+
### isValidImage Usage Example
77+
78+
```python
79+
import os
80+
from pathlib import Path
81+
82+
from multiform_validator import isValidImage
83+
84+
# Resolve the file path
85+
file_path = Path.cwd() / 'static' / 'uploads'
86+
retrieved_file = file_path / filename
87+
88+
# Read the first 4 bytes of the file
89+
with open(retrieved_file, 'rb') as f:
90+
file_buffer = f.read(4)
91+
92+
print(isValidImage(file_buffer)) # True or False
93+
```
94+
95+
## Functions signature
96+
97+
All params with default values are optional.
98+
99+
```python
100+
101+
def isEmail(email: str) -> bool:
102+
pass
103+
104+
def getOnlyEmail(text: str, multiple=False, clean_domain=False, repeat_email=False) -> str:
105+
pass
106+
107+
def passwordStrengthTester(password: str) -> str:
108+
pass
109+
110+
defaultErrorMsgCPF = [
111+
'CPF invalid',
112+
'CPF must have 11 numerical digits',
113+
'CPF is not valid',
114+
'Unknown error',
115+
]
116+
def cpfIsValid(cpf: str, errorMsg=defaultErrorMsgCPF) -> Dict[str, Union[bool, str, None]]:
117+
pass
118+
119+
default_error_msgCNPJ = [
120+
'CNPJ invalid',
121+
'CNPJ must have 14 numerical digits',
122+
'CNPJ is not valid',
123+
'Unknown error'
124+
]
125+
def cnpjIsValid(cnpj: str, errorMsg=default_error_msgCNPJ) -> Dict[str, Union[bool, str, None]]:
126+
pass
127+
128+
def isCreditCardValid(cardNumber: str) -> bool:
129+
pass
130+
131+
def identifyFlagCard(cardNumber: str) -> str:
132+
pass
133+
134+
default_error_msg = ['Invalid value passed', 'Invalid phone number', 'Unknown error']
135+
def validateBRPhoneNumber(phoneNumber: str, errorMsg=default_error_msg) -> Dict[str, Union[bool, str, None]]:
136+
pass
137+
138+
def isValidImage(file_buffer: bytes) -> bool:
139+
pass
140+
141+
```
142+
143+
## Looking for contributions.
144+
145+
## Available Validation Modules !!! STILL NOT AVALIABLE !!!
146+
147+
- **isAscii**: Checks if the string contains only ASCII characters.
148+
- **isBase64**: Checks if the string is a valid Base64 encoding.
149+
- **isCEP**: CEP validation (Brazilian postal code).
150+
- **isDate**: Date format validation.
151+
- **isDecimal**: Checks if the number is a decimal.
152+
- **isEmpty**: Checks if the string is empty.
153+
- **isMACAddress**: MAC address validation.
154+
- **isMD5**: Checks if the string is a valid MD5 hash.
155+
- **validatePassportNumber**: Passport number validation.
156+
- **isPort**: Port number validation.
157+
- **isPostalCode**: Postal code validation.
158+
- **isTime**: Time format validation.
159+
- **validateEmail**: Email address full validation.
160+
- **validatePassword**: Password validation.
161+
- **validatePhoneNumber**: Phone number validation.
162+
- **validateUsername**: Username validation.
163+
- **validateUSPhoneNumber**: US phone number validation.
164+
- **isNumber**: Checks if the value is a number.
165+
- **validateName**: Name validation.
166+
- **validateSurname**: Surname validation.
167+
- **validateTextarea**: Textarea validation.
168+
169+
### For better information, read the documentation
170+
171+
Feel free to explore the various functions and experiment with different inputs to understand their behavior. If you encounter any issues or have suggestions, don't hesitate to reach out to me. Your feedback is valuable and helps improve the package. Happy coding!
172+
173+
# By - Gabriel Logan

pyproject.toml

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
[build-system]
2+
requires = [
3+
"setuptools>=61"
4+
]
5+
build-backend = "setuptools.build_meta"
6+
7+
[project]
8+
name = "multiform-validator"
9+
version = "1.0.1"
10+
authors = [
11+
{ name="Gabriel Logan" },
12+
]
13+
description = "Multilingual library made for validation, various form fields, such as: email, cpf, cnpj, credit card, and much more."
14+
readme = "README.md"
15+
keywords = ["validator", "multiform", "validação", "email-validator", "image", "multiform-validator", "python", "security", "safe", "pentest", "security-tools", "Validator", "validate", "cpf", "cnpj", "email validator", "password", "email", "isEmail"]
16+
requires-python = ">=3.1"
17+
classifiers = [
18+
"Programming Language :: Python :: 3",
19+
"License :: OSI Approved :: MIT License",
20+
"Operating System :: OS Independent",
21+
]
22+
23+
[project.urls]
24+
"Homepage" = "https://multiform-validator.vercel.app/documentation"
25+
"Bug Tracker" = "https://github.com/gabriel-logan/multiform-validator/tree/main/packages/python"

requirements.txt

Whitespace-only changes.

src/multiform_validator/__init__.py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
from .cpfValidator import cpfValidator as cpfIsValid
2+
from .cnpjValidator import cnpjValidator as cnpjIsValid
3+
from .getOnlyEmail import getOnlyEmail
4+
from .isEmail import isEmail
5+
from .identifyFlagCard import identifyFlagCard
6+
from .isCreditCardValid import isCreditCardValid
7+
from .passwordStrengthTester import passwordStrengthTester
8+
from .validateBRPhoneNumber import validateBRPhoneNumber
9+
from .isValidImage import isValidImage
Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
def calculate_first_verifier(cnpj_base):
2+
weight = [5, 4, 3, 2, 9, 8, 7, 6, 5, 4, 3, 2]
3+
total_sum = 0
4+
for i in range(12):
5+
total_sum += cnpj_base[i] * weight[i]
6+
remainder = total_sum % 11
7+
return 0 if remainder < 2 else 11 - remainder
8+
9+
def calculate_second_verifier(cnpj_base, first_verifier):
10+
weight = [6, 5, 4, 3, 2, 9, 8, 7, 6, 5, 4, 3, 2]
11+
total_sum = 0
12+
for i in range(12):
13+
total_sum += cnpj_base[i] * weight[i]
14+
total_sum += first_verifier * weight[12]
15+
remainder = total_sum % 11
16+
return 0 if remainder < 2 else 11 - remainder
17+
18+
default_error_msg = ['CNPJ invalid', 'CNPJ must have 14 numerical digits', 'CNPJ is not valid', 'Unknown error']
19+
20+
def cnpjValidator(cnpj, errorMsg = default_error_msg):
21+
if not isinstance(cnpj, str):
22+
raise TypeError('The input should be a string.')
23+
24+
if errorMsg:
25+
if not isinstance(errorMsg, list):
26+
raise ValueError('Must be a list')
27+
for msg in errorMsg:
28+
if msg is not None and not isinstance(msg, str):
29+
raise TypeError('All values within the list must be strings or None/NoneType.')
30+
31+
def get_error_message(index):
32+
error_message = errorMsg[index]
33+
return error_message if error_message is not None else default_error_msg[index]
34+
35+
try:
36+
if not cnpj:
37+
return {
38+
'isValid': False,
39+
'errorMsg': get_error_message(0), # 'CNPJ invalid'
40+
}
41+
42+
cnpj_clean = ''.join(filter(str.isdigit, cnpj))
43+
cnpj_array = list(map(int, cnpj_clean))
44+
first_verifier = calculate_first_verifier(cnpj_array[:12])
45+
second_verifier = calculate_second_verifier(cnpj_array[:12] + [first_verifier], first_verifier)
46+
47+
if cnpj_array[12] == first_verifier and cnpj_array[13] == second_verifier:
48+
return {
49+
'isValid': True,
50+
'errorMsg': None,
51+
}
52+
53+
return {
54+
'isValid': False,
55+
'errorMsg': get_error_message(2), # 'CNPJ is not valid'
56+
}
57+
except Exception as error:
58+
return {
59+
'isValid': False,
60+
'errorMsg': get_error_message(3), # 'Unknown error'
61+
}
Lines changed: 92 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,92 @@
1+
defaultErrorMsg = [
2+
'CPF invalid',
3+
'CPF must have 11 numerical digits',
4+
'CPF is not valid',
5+
'Unknown error',
6+
]
7+
8+
def cpfValidator(cpf, errorMsg = defaultErrorMsg):
9+
"""
10+
Validates a CPF (Brazilian individual taxpayer registry identification) number.
11+
12+
:param cpf: The CPF number to be validated.
13+
:param error_msg: An optional list of error messages.
14+
:return: A dictionary with 'is_valid' (boolean) and 'error_msg' (string) properties.
15+
"""
16+
if (type(cpf) != str): raise TypeError('The input should be a string.')
17+
18+
if (errorMsg):
19+
if (not isinstance(errorMsg, list)):
20+
raise TypeError('Must be a list')
21+
for index in range(len(errorMsg)):
22+
if errorMsg[index] is not None and not isinstance(errorMsg[index], str):
23+
raise TypeError('All values within the list must be strings or None.')
24+
25+
def getErrorMessage(index):
26+
if (errorMsg and index >= 0 and index < len(errorMsg)):
27+
errorMessage = errorMsg[index]
28+
return errorMessage if errorMessage is not None else defaultErrorMsg[index]
29+
return defaultErrorMsg[index]
30+
31+
try:
32+
33+
if(not cpf):
34+
return {
35+
"isValid": False,
36+
"errorMsg": getErrorMessage(0)
37+
}
38+
39+
numeroBase = 10
40+
numeroBase2 = 11
41+
somaTotal = somaTotal2 = 0
42+
43+
if(len(cpf) != 11 and len(cpf) != 14):
44+
return {
45+
"isValid": False,
46+
"errorMsg": getErrorMessage(1),
47+
}
48+
49+
cpfLimpo = ''.join(filter(str.isdigit, cpf))
50+
51+
if (len(cpfLimpo) == 11 and cpfLimpo == cpfLimpo[0] * 11):
52+
return {
53+
"isValid": False,
54+
"errorMsg": getErrorMessage(2),
55+
}
56+
57+
primeiroVerificador = segundoVerificador = repetidor = 0
58+
59+
while (repetidor < 11):
60+
multiplicador = int(cpfLimpo[repetidor]) * numeroBase
61+
numeroBase -= 1
62+
somaTotal += multiplicador
63+
64+
multiplicador2 = int(cpfLimpo[repetidor]) * numeroBase2
65+
numeroBase2 -= 1
66+
somaTotal2 += multiplicador2
67+
68+
valorDeVerificacao = somaTotal - int(cpfLimpo[9])
69+
valorDeVerificacao2 = somaTotal2 - int(cpfLimpo[10])
70+
71+
primeiroVerificador = 11 - (valorDeVerificacao % 11)
72+
segundoVerificador = 11 - (valorDeVerificacao2 % 11)
73+
74+
repetidor += 1
75+
76+
if(primeiroVerificador > 9): primeiroVerificador = 0
77+
if(segundoVerificador > 9): segundoVerificador = 0
78+
79+
if(primeiroVerificador == int(cpfLimpo[9]) and segundoVerificador == int(cpfLimpo[10])):
80+
return {
81+
"isValid": True,
82+
"errorMsg": None,
83+
}
84+
return {
85+
"isValid": False,
86+
"errorMsg": getErrorMessage(2)
87+
}
88+
except:
89+
return {
90+
"isValid": False,
91+
"errorMsg": getErrorMessage(3),
92+
}

0 commit comments

Comments
 (0)