Created
October 4, 2017 16:24
-
-
Save echiesse/2f6391e3f3ffb394b6f3e4fa51566e28 to your computer and use it in GitHub Desktop.
Console input validation example.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class ValidationError(Exception): | |
def __init__(self, msg): | |
super().__init__(msg) | |
def weightValidator(minWeight = None, maxWeight = None): | |
def validator(val): | |
val = float(val) | |
isValid = (minWeight == None or val >= minWeight) and (maxWeight == None or val <= maxWeight) | |
msg = "ok" | |
if not isValid: | |
msg = "Erro: O valor esta fora do intervalo valido: [{}, {}]".format(minWeight, maxWeight) | |
return isValid, msg | |
return validator | |
def minLengthValidator(length): | |
def validator(val): | |
isValid = (len(val) >= length) | |
msg = "ok" | |
if not isValid: | |
msg = "Erro: O tamanho minimo deste campo eh {} caracteres".format(length) | |
return isValid, msg | |
return validator | |
def floatValidator(val): | |
isValid = True | |
msg = "ok" | |
try: | |
ret = float(val) | |
except ValueError: | |
isValid = False | |
msg = "Erro: O valor informado deve ser um numero." | |
return isValid, msg | |
def validatedInput(caption, validators): | |
ret = None | |
while True: | |
ret = input(caption) | |
try: | |
for validator in validators: | |
isValid, msg = validator(ret) | |
if not isValid: | |
raise ValidationError(msg) | |
break | |
except ValidationError as ve: | |
print(ve) | |
return ret | |
def cadastrar(gados): | |
nome = validatedInput('Informe o nome do gado => ', [minLengthValidator(3)]) | |
peso = validatedInput('Informe o peso do gado => ', [floatValidator, weightValidator(0, 500)]) | |
gados.append({'nome': nome, 'peso': peso}) | |
gados = [] | |
cadastrar(gados) | |
print(gados) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment