Date and time validation

Asked

Viewed 2,610 times

4

How do I make so that in the date field, is not saved a date that has already passed, for example yesterday and in the time field is not typed an invalid time, for example 27:00, only the Brazilian time. Both fields are MaskedTextBox.

Data Validation:

public static bool ValidaData(string maskdata)
        {
            DateTime resultado = DateTime.MinValue; 
            if (DateTime.TryParse("dd/MM/yyyy", out resultado))    
            return true; 
            return false;   

Date check:

if (clnValidacoes.ValidaData(maskdata.Text) == false)
            {
                MessageBox.Show("Data Inválida!");
                maskdata.Focus();
            }

But every date I set gives "Invalid". In time validation:

public static bool ValidaHora(string maskhora)
        {
            String hora = "";
            String[] hms = hora.split(":");
            int horas = Integer.parseInt(hms[0]);
            int segundos = Integer.parseInt(hms[2]);
            int minutos = Integer.parseInt(hms[1]);
            if (horas > 24)
            {
                return false;
            }
            else
            {
                return true;                
            }
        }
    }
}

You’re making a mistake on Interger.

  • I edited the question.

  • These codes are random and do not make sense. What is your difficulty? What do you want to result from? Give details so we can help.

  • I have a validation class with the codes, okay? Inside the Save button encoding, I put another code that will verify (through the Validation class) if the entered data is valid. I’d like you to help me with this code, because I don’t know if it’s right. In the date validation, the user cannot put a date that has already passed (example: yesterday’s) and the time cannot put a different time than our Brazilian time (example:25:00).

  • Did any of the answers below solve your problem? Do you think you can accept one of them? Check out the [tour] how to do this, if you still don’t know how to do it. This helps the community by identifying the best solution for you. You can only accept one of them, but you can vote for any question or answer you find useful on the entire site.

2 answers

2

The code posted in the question does not make sense. In fact it does not compile, it has parts that is even C#. The question also doesn’t make it very clear what the expected outcome is, but I did what I could to help.

First I pulled redundancies. It would be interesting to learn how languages actually work, all existing operators, etc. So it’s easier to make right and simplify codes.

If you want to pick a date that you know is always right (comes from a control that enters the date in set format), do not need to use the TryParse(). To get a date in specific format the ideal is to use the ParseExact(). I have my doubts if you need this or if this is the appropriate format, but I reproduced what is in the question.

To catch yesterday you have to catch today minus one. I have my doubts if this is what you need. This is a naive implementation of how to do this. You may need to look at something else.

If the time is coming from a proper control, the time should be ok, but if not the case, maybe the Split() no longer works. Would have to make a parser. As I do not know exactly what was the intention reproduced what was in the code but using C#. I have doubts whether this verification is appropriate.

public static void Main() {
    if (!ValidaData("24/10/2016")) WriteLine("invalido");
    if (!ValidaHora("27:10:15")) WriteLine("invalido");
}
public static bool ValidaData(string maskdata) => DateTime.ParseExact(maskdata, "dd/MM/yyyy", CultureInfo.InvariantCulture) <= DateTime.Now.AddDays(-1);
public static bool ValidaHora(string maskhora) => int.Parse(maskhora.Split(':')[0]) <= 24;

Behold working in the ideone. And in the .NET Fiddle. Also put on the Github for future reference.

  • It didn’t work. But thanks for the attention and patience, I’m still learning to program.

  • 1

    The @bigown code does work if it’s the way you need it, the invalid input if the time of day is for example 27:00.And also in a matter of hours it works. Or do you need real-time code not to pass, and the user not to let input pass? Even so the verification would have to be done through other means and not in real time.

0

Man, from what I understand you got two problems:

  1. You need to make sure that that’s a date
  2. This date has to be longer than the current date

The best is to work with the date and time together and check if they come together make up a valid date, and then check if the date is less than the current one:

        public static bool ValidaDataHora(string data, string hora)
        {
            DateTimeFormatInfo brDtfi = new CultureInfo("pt-BR", false).DateTimeFormat;
            try
            {
                DateTime dataehora = Convert.ToDateTime(string.Format("{0} {1}", data, hora), brDtfi);
                if(dataehora < DateTime.Now)
                {
                    return false;
                }
                else
                {
                    return true;
                }
            }
            catch
            {
                return false;
            }
        }

Browser other questions tagged

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