Create a get / set for the cpf string, which verifies that it has 11 digits, being they numbers?

0
    private static string cpf;

    public bool CPF = cpf.Length == 11 && cpf.All(char.IsDigit);

    public string Cpf
    {
        get 
        { 
            return cpf;  
        }

        set 
        {
            if(CPF)
                cpf = value;
        }
    }

When I try to create the property with the {get; set; } so this error occurs:

"An unhandled exception of type 'System.NullReferenceException' occurred in Parking.exe Additional information: Object reference not set to an instance of an object. "

    
asked by anonymous 03.03.2017 / 06:27

1 answer

2

I think the best option for you is to use a regular expression because you can have a better control of what you are validating.

And the error you are having is because you are doing the validation outside the setter.

Regex regex = Regex("[0-9]{3}\.?[0-9]{3}\.?[0-9]{3}\-?[0-9]{2}");

private static string cpf;

public string Cpf
{
    get { return cpf;  }
    set {
        if(regex.IsMatch(value))
        {
            cpf = value;
        }
    }
}
    
03.03.2017 / 13:11