I am trying to create a Regex for c# which allows only numbers (0-9) and /. The total character count should not exceed 10. This is for date text box. I have calendar extender in place, but the requirement is like, I'll have to allow the keyboard entry as well. So was trying to avoid errors
Asked
Active
Viewed 108 times
-3
-
1Show what you've tried. – rory.ap Jun 09 '15 at 14:17
-
So what happens if the user enters 9999999999? That's a valid entry according to the regex you want, but not valid as a date. – Lunyx Jun 09 '15 at 14:23
-
possible duplicate of [Regex to validate date format dd/mm/yyyy](http://stackoverflow.com/questions/15491894/regex-to-validate-date-format-dd-mm-yyyy) – Cortright Jun 09 '15 at 14:27
-
1There is no need for regex here, either just handle the individual keypresses or tryparse it as a datetime. Other than that, what have you tried? – Sayse Jun 09 '15 at 14:40
-
^(?:(?:31(\/|-|\.)(?:0?[13578]|1[02]))\1|(?:(?:29|30)(\/|-|\.)(?:0?[1,3-9]|1[0-2])\2))(?:(?:1[6-9]|[2-9]\d)?\d{2})$|^(?:29(\/|-|\.)0?2\3(?:(?:(?:1[6-9]|[2-9]\d)?(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])00))))$|^(?:0?[1-9]|1\d|2[0-8])(\/|-|\.)(?:(?:0?[1-9])|(?:1[0-2]))\4(?:(?:1[6-9]|[2-9]\d)?\d{2})$ – user2768369 Jun 09 '15 at 14:42
-
but the above is validating only dd/mm/yyyy. I want a mm/dd/yyyy – user2768369 Jun 09 '15 at 14:44
-
2DateTime d;bool valid = DateTime.TryParseExact(txtWhatever.Text, "MM/dd/yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out d) – Cortright Jun 09 '15 at 14:52
1 Answers
0
The regex expression to match numbers and the / character would be:
^[0-9/]{1,10}$
^
refers to start of string[0-9/]
refers to acceptable characters{1,10}
refers to the number of occurances$
refers to the end of the string
regexr: http://www.regexr.com/3b5uo
For a date you may want to use this regex expression:
^[0-9]{1,2}[/]{1}[0-9]{1,2}[/]{1}[0-9]{4}$
regexr: http://www.regexr.com/3b5uu

Sam Abushanab
- 492
- 3
- 13