shariq_khan
shariq_khan

Reputation: 681

error in time validation

i have a textbox which is determining the time, on the form load i have written the code so that the time will be filled in the textbox which is in this format 09:09 AM i am using the regex for validation purpose so i have wirtten this code

private bool time()
{
  Regex regex = new Regex("^(1[0-2]|0[1-9]):[0-5][0-9]\040(AM|am|PM|pm)$");
  if (regex.IsMatch(textBox2.Text))
  {
    return true;
  }
  else
  {
    return false;
  }
}

there is a button in the form which is for showing if the error is there then the error provider shows the error, and if not, then error provider doesnt blink, the code for button click is

the problem is when i keep the textbox blank and clicks the button, the error provider doesnt shows the error even if i put ''09:09 st'' instead of ''09:09 pm'' it doesnt shows error but my regex is wright

Upvotes: 0

Views: 90

Answers (3)

Rashedul.Rubel
Rashedul.Rubel

Reputation: 3584

I think blank is not checked in the textbox. In your time() function check by giving the following condition:

if(textBox2.Text=="")
return false;

thanks.

Upvotes: 0

J0HN
J0HN

Reputation: 26961

You dont' really need regexes for such a validation.

private bool time() {
    DateTime input;
    return DateTime.TryParse(textbox2.text, out input);
}

You might want to play a bit with more advanced version of TryParse to explicitly specify datetime format you expect.

See MSDN for detailed description:

  1. DateTime.TryParse
  2. DateTime.TryParse(String, IFormatProvider, DateTimeStyles, DateTime)

Also you might want to give some meaningful names to your functions, like IsValidDateTime.

Upvotes: 0

SWeko
SWeko

Reputation: 30932

You have your logic on backwards.

If the regex matches, you return true and set the error message. I guess it should be the other way around.

Also, try to give your methods (and form elements) more meaningful names like:

private bool CheckTimeFormat(string value)
{
  Regex regex = new Regex("^(1[0-2]|0[1-9]):[0-5][0-9]\040(AM|am|PM|pm)$");
  return regex.IsMatch(value);
}

private void SetInvalidTimeFormatError()
{
  bool isValidTime = CheckTimeFormat(textBox2.Text);
  if (isValidTime)
  {
    errorProvider1.SetError(textBox2, string.Empty);
  }
  else
  {
    errorProvider1.SetError(textBox2, "invalid format");
  }
}

Upvotes: 2

Related Questions