Actually you want to validate the CPF on Controller, if I understand correctly.
Implement the CPF validation attribute:
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false)]
sealed public class CpfAttribute : ValidationAttribute
{
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.");
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;
}
}
Then decorate the property with it:
[RegularExpression(@"[0-9.-]{14}", ErrorMessage = "CPF deve conter apenas números")]
[Cpf]
public string CPF { get; set; }
About not using JS in View, It’s something I’ve been trying to do for a while. I asked this question some time ago, but the answer is not 100% of what I wanted.
@Marconi there I’m only treating the Pattern, I wanted the mask in the input,
– Furlan
You want to use mask by Regularexpression?
– Marconi
@Marconi , no, I have the file js 'jquery.maskedinput.js' I say I want to use the mask in the model, so it is direct, I do not need to keep taking the #id of my inputs, got?
– Furlan
I get it, if you can ride it will be cool.
– Marconi