Created
April 19, 2017 20:51
-
-
Save drmcarvalho/3d31f6e32b9f330ee6df025e61bdecaf to your computer and use it in GitHub Desktop.
Validação de campos
This file contains hidden or 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
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
using System.Text; | |
using System.Threading.Tasks; | |
namespace ValidaCampoExemploCaffe | |
{ | |
class Pessoa | |
{ | |
public string Nome { get; set;} | |
public int Idade { get; set; } | |
public string Endereco { get; set; } | |
public double Salario { get; set; } | |
public string Cargo { get; set; } | |
} | |
class ModelPessoa | |
{ | |
//Validação Global | |
public List<string> ValidarCampos(Pessoa funcionario) | |
{ | |
var errosValidacao = new List<string>(); | |
var msgCampoObrigatorio = "{0} é obrigatorio"; | |
CampoObrigatorio("Nome", funcionario.Nome, msgCampoObrigatorio, errosValidacao); | |
CampoObrigatorio("Endereço", funcionario.Endereco, msgCampoObrigatorio, errosValidacao); | |
CampoObrigatorio("Cargo", funcionario.Cargo, msgCampoObrigatorio, errosValidacao); | |
ValorMinimo("Idade", 18, funcionario.Idade, "Funcionario deve ser maior de idade.", errosValidacao); | |
ValorMinimo("Salario", 0.01, funcionario.Salario, "Salario deve conter valor acima de zero.", errosValidacao); | |
return errosValidacao; | |
} | |
private void ValorMinimo(string nomeCampo, double valorMinimo, double valor, string mensagemPattern, List<string> errosValidacao) | |
{ | |
if (valor < valorMinimo) | |
errosValidacao.Add(string.Format(mensagemPattern, nomeCampo)); | |
} | |
private void CampoObrigatorio(string nomeCampo, string valor, string mensagemPattern, List<string> errosValidacao) | |
{ | |
if (String.IsNullOrEmpty(valor)) | |
errosValidacao.Add(string.Format(mensagemPattern, nomeCampo)); | |
} | |
} | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
Pessoa funcionario = new Pessoa(); | |
Console.Write("Nome: "); | |
funcionario.Nome = Console.ReadLine(); | |
Console.Write("Endereço: "); | |
funcionario.Endereco = Console.ReadLine(); | |
Console.Write("Cargo: "); | |
funcionario.Cargo = Console.ReadLine(); | |
Console.Write("Idade: "); | |
funcionario.Idade = Convert.ToInt32(Console.ReadLine()); | |
Console.Write("Salario: "); | |
funcionario.Salario = Convert.ToDouble(Console.ReadLine()); | |
var errosValidacao = new ModelPessoa().ValidarCampos(funcionario); | |
if (errosValidacao.Count == 0) | |
{ | |
Console.WriteLine("Cadastrado com sucesso."); | |
Console.ReadKey(); | |
return; | |
} | |
foreach (var erro in errosValidacao) | |
Console.WriteLine(erro); | |
Console.ReadKey(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment