Remote
supposes that the validation is in Controller, not in the Model.
According to your question, you own a ValidationController
which has the validation method, which is correct if the intention is to validate by Javascript. If the intention is to validate by actually persisting the record, it is necessary to implement a CPF attribute that validates the Model.
An example of a CPF validation attribute of the type string
is below, considering points and traits:
using System;
using System.ComponentModel.DataAnnotations;
using SeuProjeto.Models;
namespace SeuProjeto.Attributes
{
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false)]
sealed public class CpfAttribute : ValidationAttribute
{
private MaxiMailContext context = new MaxiMailContext();
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
if (value == null) return null;
int soma = 0, resto = 0;
string digito;
int[] multiplicador1 = new int[9] { 10, 9, 8, 7, 6, 5, 4, 3, 2 };
int[] multiplicador2 = new int[10] { 11, 10, 9, 8, 7, 6, 5, 4, 3, 2 };
string CPF = value.ToString().Replace(".", "").Replace("-", "");
if (CPF.Length != 11)
return new ValidationResult("CPF Inválido.");
if (Convert.ToUInt64(CPF) % 11111111111 == 0)
return new ValidationResult("CPF Inválido.");
decimal CPFDecimal = Convert.ToDecimal(CPF);
/* if (validationContext.ObjectInstance.GetType() == typeof(Customer))
{
var model = (Customer)validationContext.ObjectInstance;
if (context.Customers.Any(c => (c.CPF == CPFDecimal) && (c.CustomerId != model.CustomerId)))
{
var message = FormatErrorMessage("CPF já está cadastrado em outra conta de cliente.");
return new ValidationResult(message);
}
}
else
{
if (context.Customers.Any(c => (c.CPF == CPFDecimal)))
{
var message = FormatErrorMessage("CPF já está cadastrado em outra conta de cliente.");
return new ValidationResult(message);
}
} */
string tempCpf = CPF.Substring(0, 9);
for (int i = 0; i < 9; i++)
soma += int.Parse(tempCpf[i].ToString()) * multiplicador1[i];
resto = soma % 11;
if (resto < 2)
resto = 0;
else
resto = 11 - resto;
digito = resto.ToString();
tempCpf = tempCpf + digito;
soma = 0;
for (int i = 0; i < 10; i++)
soma += int.Parse(tempCpf[i].ToString()) * multiplicador2[i];
resto = soma % 11;
if (resto < 2)
resto = 0;
else
resto = 11 - resto;
digito = digito + resto.ToString();
if (CPF.EndsWith(digito))
return null;
else
return new ValidationResult("CPF Inválido.");
}
public override string FormatErrorMessage(string name)
{
return name;
}
}
}
Hello @Marco, my problem is not validation, but inheritance of properties
– Rod
So do what the Gypsy downstairs said.
– Marco Antonio Quintal
it doesn’t make sense that, I’ll see what I do
– Rod