protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            if (value == null)
            {
                return(new ValidationResult("Informe o documento"));
            }

            string documento = value.ToString();

            if (documento.Length <= 11)
            {
                if (!CpfValidation.Validar(documento))
                {
                    return(new ValidationResult("O CPF informado é inválido."));
                }
            }
            else
            {
                if (!CnpjValidation.Validar(documento))
                {
                    return(new ValidationResult("O CNPJ informado é inválido."));
                }
            }

            return(ValidationResult.Success);
        }
Beispiel #2
0
        public void Cpf_ValidarMultiplosNumeros_TodosDevemSerInvalidos(string cpf)
        {
            //Assert
            var cpfValidation = new CpfValidation();

            cpfValidation.EhValido(cpf).Should().BeFalse();
        }
        public Response Add(ClienteDto clienteDto)
        {
            #region Validation
            if (clienteDto.IsNotValid())
            {
                return(Response.BuildBadRequest(ExceptionMessages.ObjetoInvalido));
            }

            if (!clienteDto.CpfValid())
            {
                return(Response.BuildBadRequest(ExceptionMessages.CpfInvalido));
            }

            if (_clienteRepository.Any(CpfValidation.Limpa(clienteDto.Cpf)))
            {
                return(Response.BuildBadRequest(ExceptionMessages.CpfJaCadastrado));
            }
            #endregion

            var cliente = _clienteRepository
                          .Add(_mapper.Map <Cliente>(clienteDto));

            if (!_unitOfWork.Commit())
            {
                throw new ExceptionHttp(ExceptionMessages.ErroAoSalvarDados);
            }

            return(Response.BuildSuccess(_mapper.Map <ClienteDto>(cliente)));
        }
        public FornecedorValidation()
        {
            RuleFor(x => x.Nome)
            .NotEmpty().WithMessage("O campo {PropertyName} precisa ser preechido")
            .Length(2, 100)
            .WithMessage("O campo {PropertyName} precisa ter entre {MinLength} e {MaxLength} caracteres");

            When(x => x.TipoFornecedor == TipoFornecedor.PessoaFisica, () =>
            {
                RuleFor(x => x.Documento.Length).Equal(CpfValidation.TamanhoCpf)
                .WithMessage("O campo Documento precisa ter {ComparisonValue} caracteres e foi fornecido {PropertyValue}.");

                RuleFor(x => CpfValidation.Validar(x.Documento)).Equal(true)
                .WithMessage("O documento fornecido é inválido.");
            });

            When(x => x.TipoFornecedor == TipoFornecedor.PessoaJuridica, () =>
            {
                RuleFor(x => x.Documento.Length).Equal(CnpjValidation.TamanhoCnpj)
                .WithMessage("O campo Documento precisa ter {ComparisonValue} caracteres e foi fornecido {PropertyValue}.");

                RuleFor(x => CnpjValidation.Validar(x.Documento)).Equal(true)
                .WithMessage("O documento fornecido é inválido.");
            });
        }
        public void Cpf_ValidarMultiplosNumeros_TodosDevemSerValidos(string cpf)
        {
            //Arrange
            var cpfValidation = new CpfValidation();

            //Act & Assert
            cpfValidation.EhValido(cpf).Should().BeTrue();
        }
        public void Cpf_ValidateMultipleNumbers_AllShouldInvalid(string cpf)
        {
            // Assert
            var cpfValidation = new CpfValidation();

            // Act & Assert
            cpfValidation.IsValid(cpf).Should().BeFalse();
        }
        public void CpfValidation_Validate_ShouldCheckIfCpfIsValid(string validCpf, string invalidCpf)
        {
            // Act
            var validResult   = CpfValidation.Validate(validCpf);
            var invalidResult = CpfValidation.Validate(invalidCpf);

            // Assert
            Assert.True(validResult);
            Assert.False(invalidResult);
        }
        public override bool IsValid(object value)
        {
            var cpf = value?.ToString();

            if (string.IsNullOrEmpty(cpf) && !IsRequired)
            {
                return(true);
            }

            return(CpfValidation.IsValid(cpf));
        }
Beispiel #9
0
        /// <summary>
        /// Validação server
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public override bool IsValid(object value)
        {
            if (value == null || string.IsNullOrEmpty(value.ToString()))
            {
                return(true);
            }

            bool valido = CpfValidation.ValidateCpf(value.ToString());

            return(valido);
        }
        public ProviderValidation()
        {
            RuleFor(p => p.Name)
            .NotEmpty().WithMessage("O campo {PropertyName} não pode ser vazio")
            .Length(3, 100).WithMessage("O campo precisa ter entre {MinLength} e {MaxLength} caracteres");

            When(p => p.ProviderType == ProviderType.LegalPerson, () => {
                RuleFor(p => p.DocumentNumber.Length).Equal(CnpjValidation.TamanhoCnpj).WithMessage("O campo precisa ter {ComparisonValue} caracteres");
                RuleFor(p => CnpjValidation.Validar(p.DocumentNumber)).Equal(true).WithMessage("O documento fornecido é inválido");
            });
            When(p => p.ProviderType == ProviderType.PhysicalPerson, () => {
                RuleFor(p => p.DocumentNumber.Length).Equal(CpfValidation.TamanhoCpf).WithMessage("O campo precisa ter {ComparisonValue} caracteres");
                RuleFor(p => CpfValidation.Validar(p.DocumentNumber)).Equal(true).WithMessage("O documento fornecido é inválido");
            });
        }
        public EmployeeValidation()
        {
            RuleFor(e => e.FirstName)
            .NotEmpty().WithMessage("The field {PropertyName} must be provided")
            .Length(2, 50).WithMessage("The field {PropertyName} need to have between {MinLength} and {MaxLength} characteres");

            RuleFor(e => e.LastName)
            .NotEmpty().WithMessage("The field {PropertyName} must be provided")
            .Length(2, 50).WithMessage("The field {PropertyName} need to have between {MinLength} and {MaxLength} characteres");

            RuleFor(e => e.Document.Length).Equal(CpfValidation.CpfLength)
            .WithMessage("O campo Documento precisa ter {ComparisonValue} caracteres e foi fornecido {PropertyValue}");
            RuleFor(f => CpfValidation.Validate(f.Document)).Equal(false)
            .WithMessage("O documento fornecido é inválido.");
        }
        public override bool IsValid(object value)
        {
            bool result;
            int  parsedValue = Convert.ToInt32(value);

            if (parsedValue > 0)
            {
                result = CpfValidation.IsValid(parsedValue);
            }
            else
            {
                result = CpfValidation.IsValid(value as string);
            }

            return(result);
        }
        public ClienteValidation()
        {
            RuleFor(f => f.NomeCompleto)
            .NotEmpty().WithMessage("O campo {PropertyName} é obrigatório!")
            .Length(2, 255).WithMessage("O campo {PropertyName} precisa ter entre {MinLength} e {MaxLength} caracteres!");

            When(f => f.TipoPessoa == ETipoPessoa.PessoaFisica, () =>
            {
                RuleFor(f => CpfValidation.IsCpf(f.CpfCnpj)).Equal(true).WithMessage("O CPF é inválido!");
            });

            When(f => f.TipoPessoa == ETipoPessoa.PessoaJuridica, () =>
            {
                RuleFor(f => CnpjValidation.IsCnpj(f.CpfCnpj)).Equal(true).WithMessage("O CNPJ é inválido!");
            });
        }
        public Response Login(LoginDto loginDto)
        {
            if (loginDto.IsNotValid())
            {
                return(Response.BuildBadRequest(ExceptionMessages.CpfESenhaEmBranco));
            }

            var cliente = _clienteAppService.ObterPorCpfESenha(CpfValidation.Limpa(loginDto.Cpf), loginDto.Senha);

            if (cliente == null)
            {
                return(Response.BuildBadRequest(ExceptionMessages.ClienteNaoEncontrado));
            }

            return(Response.BuildSuccess(_jwtService.CreateJsonWebToken(cliente)));
        }
Beispiel #15
0
        public SupplierValidation()
        {
            RuleFor(x => x.Name)
            .NotEmpty().WithMessage("The field {PropertyName} is required.")
            .Length(2, 100).WithMessage("The field {PropertyName} must have between {MinLenght} and {MaxLength} characters.");
            When(x => x.SupplierType == SupplierType.PF, () =>
            {
                RuleFor(x => x.Document.Length).Equal(CpfValidation.CpfSize).WithMessage("The document field must have {ComparisonValue} characters.");
                RuleFor(x => CpfValidation.Validate(x.Document)).Equal(true).WithMessage("The document provided is invalid.");
            });

            When(f => f.SupplierType == SupplierType.PJ, () =>
            {
                RuleFor(f => f.Document.Length).Equal(CnpjValidation.CnpjSize).WithMessage("The Document field must have {ComparisonValue} characters.");
                RuleFor(f => CnpjValidation.Validate(f.Document)).Equal(true).WithMessage("The document provided is invalid.");
            });
        }
        private string TratarCampoCpf(ValorReconhecido valorReconhecido)
        {
            if (valorReconhecido == null || string.IsNullOrEmpty(valorReconhecido.Value))
            {
                return(string.Empty);
            }

            var match = Regex.Match(valorReconhecido.Value, @"[0-9]{3}[ ./\-]{0,1}[0-9]{3}[ ./\-]{0,1}[0-9]{3}[ ./\-]{0,1}[0-9]{2}");

            if (match.Success)
            {
                var validaCpf = new CpfValidation();
                if (validaCpf.IsValid(match.Value.ObterInteiros()))
                {
                    return(match.Value.ObterInteiros());
                }
            }

            return(string.Empty);
        }
Beispiel #17
0
        private async Task afterHire(IDialogContext context, IAwaitable <string> result)
        {
            string        cpf        = await result;
            CpfValidation validation = new CpfValidation();
            bool          valid      = validation.Valida(cpf);

            if (valid == false)
            {
                await context.PostAsync("CPF incorreto");

                PromptDialog.Text(context, afterHire, "Informe novamente seu CPF");
            }
            else
            {
                user.cpf = cpf;
                await context.PostAsync("Os detalhes da contratação serão enviados por e-mail.");

                PromptDialog.Text(context, addEmail, "Nos informe seu e-mail por favor.");
            }
        }
Beispiel #18
0
        public SupplierValidation()
        {
            RuleFor(s => s.Name)
            .NotEmpty()
            .WithMessage("O campo {PropertyName} é obrigatório")
            .Length(2, 100)
            .WithMessage("O campo {PropertyName} precisa ter entre {MinLength} e {MaxLength} caracteres");

            When(s => s.SupplierType == SupplierType.IndividualRegistration, () =>
            {
                RuleFor(s => s.Document.Length).Equal(CpfValidation.CPF_LENGTH)
                .WithMessage("O campo Documento precisa ter {ComparisonValue} caracteres e foi fornecido {PropertyValue}");
                RuleFor(s => CpfValidation.Validate(s.Document)).Equal(true)
                .WithMessage("O CPF está em formato inválido");
            });

            When(s => s.SupplierType == SupplierType.LegalEntityRegistration, () =>
            {
                RuleFor(s => s.Document.Length).Equal(CnpjValidation.CNPJ_LENGTH)
                .WithMessage("O campo Documento precisa ter {ComparisonValue} caracteres e foi fornecido {PropertyValue}");
                RuleFor(s => CnpjValidation.Validate(s.Document)).Equal(true)
                .WithMessage("O CNPJ está em formato inválido");
            });
        }
Beispiel #19
0
        public ProviderValidation()
        {
            RuleFor(p => p.Name)
            .NotEmpty().WithMessage("O Campo {PropertyName} precisa ser informado.")
            .Length(min: 2, max: 100).WithMessage("O Campo {PropertyName} precisa ter entre {MinLength} e {MaxLength} caracteres");

            When(f => f.ProviderType == ProviderType.PhysicalPerson, () =>
            {
                RuleFor(f => f.Document.Length)
                .Equal(CpfValidation.CpfLength)
                .WithMessage("O Campo Documento precisa ter {ComparisonValue} caracteres e foi fornecido {PropertyValue}");
                RuleFor(f => CpfValidation.Validate(f.Document)).Equal(true)
                .WithMessage("O Documento fornecido é inválido");
            });

            When(f => f.ProviderType == ProviderType.LegalPerson, () =>
            {
                RuleFor(f => f.Document.Length)
                .Equal(CnpjValidation.CpfLength)
                .WithMessage("O Campo Documento precisa ter {ComparisonValue} caracteres e foi fornecido {PropertyValue}");
                RuleFor(f => CnpjValidation.Validate(f.Document)).Equal(true)
                .WithMessage("O Documento fornecido é inválido");
            });
        }
Beispiel #20
0
        public SupplierValidation()
        {
            RuleFor(s => s.Name)
            .NotEmpty().WithMessage("{PropertyName} field must be provided")
            .Length(2, 100).WithMessage("{PropertyName field must be between {MinLength} and {MaxLength} characters}");

            When(s => s.SupplierType == SupplierType.NaturalPerson, () =>
            {
                RuleFor(s => s.Document.Length).Equal(CpfValidation.CpfSize)
                .WithMessage("Document field must be {ComparisonValue} characters long and has been provided {PropertyValue}.");

                RuleFor(s => CpfValidation.Validate(s.Document)).Equal(true)
                .WithMessage("The document provided is invalid");
            });

            When(s => s.SupplierType == SupplierType.LegalEntity, () =>
            {
                RuleFor(s => s.Document.Length).Equal(CnpjValidation.CnpjSize)
                .WithMessage("Document field must be {ComparisonValue} characters long and has been provived {PropertyValue}");

                RuleFor(s => CnpjValidation.Validate(s.Document)).Equal(true)
                .WithMessage("The document provided is invalid");
            });
        }
Beispiel #21
0
 public bool Validate()
 {
     return(CpfValidation.Validar(this.Document));
 }
 public bool IsSatisfiedBy(Usuario usuario)
 {
     return(CpfValidation.Validar(usuario.Cpf));
 }
Beispiel #23
0
 private void ValidarCpf() =>
 RuleFor(c => CpfValidation.Validar(c.Cpf))
 .Equal(true).WithMessage("O CPF deve ser válido.");
Beispiel #24
0
 public void TestCpfInvalid()
 {
     CpfValidation.IsValid("123.123.123-12");
 }
Beispiel #25
0
 public void TestCpfValid()
 {
     CpfValidation.IsValid("329.191.658-10");
 }
Beispiel #26
0
 public bool IsSatisfiedBy(Proposta proposta)
 {
     return(CpfValidation.Validar(proposta.CPF_CNPJ));
 }
Beispiel #27
0
 public bool IsValid()
 {
     return(!string.IsNullOrWhiteSpace(Nome) && CpfValidation.IsValid(Cpf));
 }
Beispiel #28
0
        public async Task <JsonResult> AdicionarCliente(ClienteViewModel clienteModel)
        {
            _clienteRepository = new ClienteRepository(_context);
            var mensagens = new List <Mensagem>();
            var sucesso   = true;

            //valida cpf
            clienteModel.Cpf     = clienteModel.Cpf.Trim();
            clienteModel.Nome    = clienteModel.Nome.Trim();
            clienteModel.Email   = clienteModel.Email.Trim();
            clienteModel.Empresa = clienteModel.Empresa.Trim();
            clienteModel.TelefoneComercialDdd = clienteModel.TelefoneComercialDdd.Trim();
            clienteModel.TelefoneComercial    = clienteModel.TelefoneComercial.Trim();
            clienteModel.CelularDdd           = clienteModel.CelularDdd.Trim();
            clienteModel.Celular = clienteModel.Celular.Trim();

            if (String.IsNullOrEmpty(clienteModel.Nome))
            {
                mensagens.Add(new Mensagem
                {
                    Tipo  = ETipoMensagem.Falha,
                    Texto = "Nome do cliente não informado, este campo é obrigatório."
                });
                sucesso = false;
            }
            if (String.IsNullOrEmpty(clienteModel.Email))
            {
                mensagens.Add(new Mensagem
                {
                    Tipo  = ETipoMensagem.Falha,
                    Texto = "E-mail do cliente não informado, este campo é obrigatório."
                });
                sucesso = false;
            }

            if (!String.IsNullOrEmpty(clienteModel.Cpf))
            {
                //Valida se o CPF é um CPF válido
                if (CpfValidation.Validar(clienteModel.Cpf))
                {
                    //Verifica no banco de dados se este cpf já esta cadastrado
                    if (await _clienteRepository.CpfExistente(clienteModel.Cpf))
                    {
                        mensagens.Add(new Mensagem
                        {
                            Tipo  = ETipoMensagem.Falha,
                            Texto = "Cliente já cadastrado, não é possível cadastrar novamente."
                        });
                        sucesso = false;
                    }
                }
                else
                {
                    mensagens.Add(new Mensagem
                    {
                        Tipo  = ETipoMensagem.Falha,
                        Texto = "CPF esta em um formato inválido, por favor verifique."
                    });
                    sucesso = false;
                }
            }
            else
            {
                mensagens.Add(new Mensagem
                {
                    Tipo  = ETipoMensagem.Falha,
                    Texto = "CPF não foi informado"
                });
                sucesso = false;
            }

            //somente maiores de 18 podem ser cadastrados
            if (clienteModel.DataNascimento == null)
            {
                mensagens.Add(new Mensagem
                {
                    Tipo  = ETipoMensagem.Falha,
                    Texto = "Data de nascimento não informado, este campo é obrigatório."
                });
                sucesso = false;
            }
            else
            {
                if (clienteModel.DataNascimento.AddYears(18) < DateTime.Now)
                {
                    mensagens.Add(new Mensagem
                    {
                        Tipo  = ETipoMensagem.Falha,
                        Texto = "Cliente tem menos de 18 anos e não pode prossegir o cadastro."
                    });
                    sucesso = false;
                }
            }

            //Insere o cliente no banco
            var cliente = new Cliente
            {
                Nome                 = clienteModel.Nome,
                Cpf                  = clienteModel.Cpf,
                DataNascimento       = clienteModel.DataNascimento,
                Email                = clienteModel.Email,
                Empresa              = clienteModel.Empresa,
                TelefoneComercialDdd = clienteModel.TelefoneComercialDdd,
                TelefoneComercial    = clienteModel.TelefoneComercial,
                Celular              = clienteModel.Celular,
                CelularDdd           = clienteModel.CelularDdd,
                Idade                = DateTime.Now.Year - clienteModel.DataNascimento.Year
            };

            //insere no banco
            try
            {
                await _clienteRepository.AddAndSaveAsync(cliente);

                mensagens.Add(new Mensagem
                {
                    Tipo  = ETipoMensagem.Sucesso,
                    Texto = "Formulário enviado com sucesso. Em breve entraremos em contato."
                });
            }
            catch (Exception e)
            {
                return(Json(new { Sucesso = false, erro = e.InnerException != null ? e.InnerException.Message : e.Message }));
            }

            //mensagem de sucesso "Formulário enviado com sucesso. Em breve entraremos em contato."
            return(Json(new
            {
                Sucesso = sucesso,
                Mensagens = mensagens
            }));
        }
Beispiel #29
0
 public bool IsSatisfiedBy(Cliente cliente)
 {
     return(CpfValidation.Validar(cliente.CPF));
 }
Beispiel #30
0
 public bool IsSatisfiedBy(Cliente entity)
 {
     return(CpfValidation.Validar(entity.CPF));
 }