Validation using Remote in class "PaI"

2

I have my Person class, it has the CPF property

public class Pessoa {
   public string Cpf {get;set;}
}

Other classes inherit from it, such as the Client class

public class Cliente : Pessoa {
}

It turns out that I use Data Annotation Remote

[Remote("CheckCpf", "Validation", AdditionalFields = "Id", ErrorMessage = "Mensagem.")]

How can I use Remote validating on each class that inherits from Person?

For example: Customer:

 [Remote("CheckCpfCLIENTE", "Validation", AdditionalFields = "Id", ErrorMessage = "Mensagem.")]

Provider:

 [Remote("CheckCpfFornecedor", "Validation", AdditionalFields = "Id", ErrorMessage = "Mensagem.")]
    
asked by anonymous 14.01.2015 / 14:12

3 answers

1

Remote assumes that validation is in Controller , not in Model .

Depending on your question, you have a ValidationController that has the validation method, which is correct if the purpose is to validate by JavaScript. If the intent is to validate when de facto registration persists, you must implement a CPF attribute that validates Model .

An example of a CPF validation attribute of type string is below, considering points and dashes:

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;
        }
    }
}
    
14.01.2015 / 14:29
1
___ erkimt ___ Validation using Remote in class "PaI" ______ qstntxt ___

I have my Person class, it has the CPF property

%pre%

Other classes inherit from it, such as the Client class

%pre%

It turns out that I use %code%

%pre%

How can I use %code% validating on each class that inherits from Person?

For example: Customer:

%pre%

Provider:

%pre%     
______ azszpr46875 ___

%code% assumes that validation is in Controller , not in Model .

Depending on your question, you have a %code% that has the validation method, which is correct if the purpose is to validate by JavaScript. If the intent is to validate when de facto registration persists, you must implement a CPF attribute that validates Model .

An example of a CPF validation attribute of type %code% is below, considering points and dashes:

%pre%     
______ ___ azszpr46874

One way to do this is to search directly with ADO.Net but I advise you to use an ORM. Are you working with any ORM? NHibernate or EF.

If you let me know, I'll try to show you how to do it. Send your remote validation code as well.

Take a look also at my blog. I made a post there that answered a question here about remote validation. Remember to always validate the ID also is it if you do this you will have problems to change their objects as it will appear that already exists in the database.

There you can download a project in asp net mvc 5 with remote validation working well. link

    
______ azszpr46881 ___

Like all classes that inherit from person, it also has the CPF property, I did as follows:

In class Person I leave my CPF property as virtual

%pre%

In my Client class, for example, I override the person's CPF property:

%pre%

And I do the same thing in other classes that inherit from Person, changing only the "Action" and "Controller" of the remote

%pre%

etc

    
___
14.01.2015 / 14:27
1

Like all classes that inherit from person, it also has the CPF property, I did as follows:

In class Person I leave my CPF property as virtual

public virtual string CPF {get;set;}

In my Client class, for example, I override the person's CPF property:

    [Remote("CheckCpfCliente", "Cliente", AdditionalFields = "Id", ErrorMessage = "Mensagem erro")]
    public override string CPF
    {
        get
        {
            return base.CnpjCpf;
        }
        set
        {
            base.CnpjCpf = value;
        }
    }

And I do the same thing in other classes that inherit from Person, changing only the "Action" and "Controller" of the remote

  [Remote("CheckCpfFORNECEDOR, "FORNECEDOR")
  [Remote("CheckCpfFUNCIONARIO, "FUNCIONARIO")

etc

    
14.01.2015 / 14:45