Check if a date is valid

Asked

Viewed 1,886 times

2

I have a college job where I need to check if a date is valid but I can’t use the classes Datetime and Timespan. With these classes I can do it, but without being able to use them by the criteria of the teacher I am not able to do it. The image shows how the project should look, the rest I’ve done, only need to check whether the date that is typed is valid or not! Can someone give me some hint how to try to solve this way?

inserir a descrição da imagem aqui

3 answers

1


I think you can split the Maskedtextbox string into a split, using the '/' character, convert the numbers to integer and then validate.

In the MaskedTextBox, the property TextMaskFormat should be like IncludeLiterals which is the default setting.

Following example:

public static void Main()
{
    string data = "31/03/2018"; //Aqui você coloca: seuMaskedTextBox.Text;

    int maiorAnoPermitido = 2050;
    int menorAnoPermitido = 2000;

    string[] val = data.Split('/');

    int dia, mes, ano;

    if (int.TryParse(val[0] , out dia) && int.TryParse(val[1], out mes) && int.TryParse(val[2], out ano))
    {
                if (ano >= menorAnoPermitido && ano <= maiorAnoPermitido)
                {
                    if (mes >=1 && mes <=12)
                    {

                        int maxDia = (mes==2 ? ( ano % 4 ==0 ? 29 : 28  ) : mes <=7 ? (mes%2==0?30 : 31) : (mes%2==0?31:30));                       

                        if (dia >=1 && dia <=maxDia)
                        {
                            Console.WriteLine("Data Válida");
                        }
                        else
                        {
                            Console.WriteLine("Dia inválido");
                        }
                    }
                    else
                    {
                        Console.WriteLine("Mês inválido");
                    }
                }
                else
                {
                    Console.WriteLine("Ano inválido");
                }
    }
    else
    {
        Console.WriteLine("Data inválida");
    }

}

Now, with more time, I did the validation including the days next to the month, besides defining variables for the largest and smallest year that the system should accept.

I put in the . Netfiddle: https://dotnetfiddle.net/oTRN3k

  • Thanks for the tip, I’m going through the code to see what I can implement, already gave a clear!

  • If the smart-ass Q gave down can show up and give the review, thank you... I imagine the reason kkkk

  • 1

    @Rovannlinhalis alive taking of these :)

  • Only one hypothesis: it may have been because the above code allows invalid dates (February 31) and considers certain valid dates invalid (i.e.: 01/01/1890).

  • the part of the invalid dates, I quoted in the answer and just increment the checks, the part of valid dates as invalid, I believe it is at the discretion of the programmer, in the scenario that he is believe register a name information, Cpf, invalid email as of 01/01/1890 entry date, it is sufficient for it to define which years will be valid for the user to enter the @Renan record

  • 1

    @Rovannlinhalis Solved yes, thank you!

  • 1

    @Rovannlinhalis marquei

Show 2 more comments

0

Although the object returned by Convert.ToDateTime be the type DateTime, was not used directly from the class DateTime... I guess it could be like this:

bool validaData;

try {
    Convert.ToDateTime(txtData.Text);
    validaData = true;
} catch (Exception exx) {
    validaData = false;
}

if(validaData){
    //Válida!
} else {
    //Não é válida!
}

0

You can get portions of the text from the field and turn into numbers:

string textoBruto = this.TextBoxN.Text;
int dia = Convert.ToInt32(textoBruto.Substring(0, 2), 10); // onde 10 significa base decimal
int mes = Convert.ToInt32(textoBruto.Substring(2, 2), 10);
int ano = Convert.ToInt32(textoBruto.Substring(4, 4), 10);

I suppose the bars are not part of the text... I don’t remember how this component behaves, but if there are bars, just take with a Replace.

And if those conversions go wrong, it’s because they weren’t valid integers anyway.

Now just do two simple checks: whether the month is between 1 and 12, and whether the days are between 1 and the maximum of the month.

if (mes < 1 || mes > 12) {
    throw new DataInvalidaMeuParsaException();
}

A tip to catch the biggest possible day of the month: you can create a hashmap, or cheat with an Array:

int[] maioresDias = new int[] {
    31,
    ano % 4 == 0 ? 29 : 28, // verificação de bissexto
    31, 30, 31, 30, 31, 31, 30, 31, 30, 31
};

And now:

if (dia < 1 || dia > maioresDias[mes - 1]) {
    throw new ParaCeTaLokException();
}

P.s.: merely illustrative exceptions. . NET has some more appropriate types of exceptions that already come with it, such as ArgumentException or ArgumentOutOfRangeException.

  • Thank you, I’ll see what I can do having an idea in your information

Browser other questions tagged

You are not signed in. Login or sign up in order to post.