I am looking for a Regular expression to match only if a date is in the first 28 days of the month. This is for my validator control in ASP.NET
Don't do this with Regex. Dates are formatted differently in different countries. Use the DateTime.TryParse routine instead:
DateTime parsedDate;
if ( DateTime.TryParse( dateString, out parsedDate) && parsedDate.Day <= 28 )
{
// logic goes here.
}
Regex is nearly the golden hammer of input validation, but in this instance, it's the wrong choice.
I don't think this is a task very well-suited for a regexp.
I'd try and use the library functions (DateTime.Parse for .NET) to parse the date and then check the day component of it. Everything else is duplicating half the library function anyways.
Why not just covert it to a date data type and check the day? Using a regular expression, while it could be done, just makes it overly complicated.
([1-9]|1\d|2[0-8]) // matches 1 to 28 but woudn't allow leading zeros for single digits
(0?[1-9]|1\d|2[0-8]) // matches 1 to 28 and would allow 01, 02,... 09
(where \d matches any digit, use [0-9] if your regex engine doesn't support it.)
See also the question What is the regex pattern for datetime (2008-09-01 12:35:45 ) ?
I would use one of the DateTime.TryParse techniques in conjunction with a CustomValidator
Related
I want to check the date which must be in the format dd-mm-yyyy using a regular expression, and it also must check the leap year dates.
I am using RegularExpressionValidator for checking the date.
try this. It works for me!
ValidationExpression="(^((((0[1-9])|([1-2][0-9])|(3[0-1]))|([1-9]))-(((0[1-9])|(1[0-2]))|([1-9]))-(([0-9]{2})|(((19)|([2]([0]{1})))([0-9]{2}))))$)"
Try this regular expression-
^(((((0[1-9])|(1\d)|(2[0-8]))-((0[1-9])|(1[0-2])))|((31-((0[13578])|(1[02])))|((29|30)-((0[1,3-9])|(1[0-2])))))-((20[0-9][0-9]))|(29-02-20(([02468][048])|([13579][26]))))$
Got it from Here
This regex also handles leap year:
^(((0[1-9]|[12]\d|3[01])/(0[13578]|1[02])/((19|[2-9]\d)\d{2}))|((0[1-9]|[12]\d|30)/(0[13456789]|1[012])/((19|[2-9]\d)\d{2}))|((0[1-9]|1\d|2[0-8])/02/((19|[2-9]\d)\d{2}))|(29/02/((1[6-9]|[2-9]\d)(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00))))$
Matches
[29/02/2000], [30/04/2003], [01/01/2003]
Non-Matches
[29/02/2001], [30-04-2003], [1/1/1899]
You can also check this link out: http://www.codeproject.com/KB/aspnet/LengthValidation.aspx
You can javascript to check leap year for more info
isLeap = new Date(year, 1, 29).getMonth() == 1
Regular Expression
^(?:^(?:(?:(?:(?:(?:0?[13578]|1[02])/31)|(?:(?:0?[13-9]|1[0-2])/(?:29|30)))/(?:1[6-9]|[2-9]\d)\d{2})|(?:0?2/29/(?:(?:(?:1[6-9]|[2-9]\d)(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])00))))|(?:(?:0?[1-9])|(?:1[0-2]))/(?:0?[1-9]|1\d|2[0-8])/(?:(?:1[6-9]|[2-9]\d)\d{2}))$)$
These allow but do not require a leading zero in single-digit months/days. If you don't want that, replace all instances of 0? with 0.
You could use a CustomValidator and have the client-side validation be simple and on the server-side use a DateTime.TryParse to get a definitive validation. Although I suspect you don't need your code to work all the way to the year 9999 (no, I couldn't immediately see if the supplied regexes work that far into the future).
from Microsoft DN but modified to work with years both 20xx and 19xx to used as DOB
^(((((0[1-9])|(1\d)|(2[0-8]))/((0[1-9])|(1[0-2])))|((31-((0[13578])|(1[02])))|((29|30)-((0[1,3-9])|(1[0-2])))))/((((20[0-9][0-9]))|(29-02-20(([02468][048])|([13579][26]))))|(((19[0-9][0-9]))|(29-02-19(([02468][048])|([13579][26]))))))$
for dd/MM/yyyy formate
(((0|1)[0-9]|2[0-9]|3[0-1])\/(0[1-9]|1[0-2])\/((19|20)\d\d))$
I need to validate a decimal number in asp.net. I thought to use a RegularExpressionValidator. In case you have another idea just suggest me.
The number must match numeric(4,1) so accepted values would be:
1; 12; 123; 123,1; (not good: 1234; 12,34; 1,234)
I tried to use this expression:
^\d{1,3}(\,\d{0,1})$
but something is not good with this one.
If you have a comma, then the following digit is not optional, so you need to make the whole group optional, not only the digit.
^\d{1,3}(,\d)?$
See it here on Regexr
? is short for {0,1}
I am not expert in writing regular expressions so need your help. I want to validate date in "dd-MMM-yyyy" format i.e. 07-Jun-2012. I am using RegularExpressionValidator in asp.net.
Can anybody help me out providing the expression?
Thanks for sharing your time.
Using a DatePicker is probably the best approach. However, since that's not what you asked, here's an option (although it's case sensitive):
^(([0-9])|([0-2][0-9])|([3][0-1]))\-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\-\d{4}$
In addition, here's a place you can easily test Regular Expressions: http://www.regular-expressions.info/javascriptexample.html
Regex without leading zero in day.
^\d{1,2}-[a-zA-Z]{3}-\d{4}$
Update Regex with leading zero in day.
^\d{2}-[a-zA-Z]{3}-\d{4}$
It's not regex, but you can use build in DateTime.TryParseExact function to validate your datetime string
DateTime dateTime;
string toValidate = "01-Feb-2000";
bool isStringValid = DateTime.TryParseExact(
toValidate,
"dd-MMM-yyyy",
CultureInfo.InvariantCulture,
DateTimeStyles.None,
out dateTime);
The accepted solution allows '00' as the day, so here is a fix for that:
^(([1-9])|([0][1-9])|([1-2][0-9])|([3][0-1]))\-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\-\d{4}$
Notes/Exceptions:
1.Be aware of case sensitivity issues. Eg. 'DEC' will not pass while 'Dec' will pass. You may want to convert the regex string and test string to lowercase before testing (if your application allows).
2.This will not catch days that don't exist, like Feb 30th, June 31st, etc.
"\d{4}\d{2}\d{2}|\d{2}/\d{2}/\d{4}|\d{2}.\d{2}.\d{4}|\d{2}\-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)|(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)-\d{2}\-\d{4}|\d{4}-\d{2}-\d{2}"
These format is mm.dd.yyyy, d-MMM, mm.dd.yyyy
Yet another idea would be to try this (similar to user1441894's idea):
var x = DateTime.Parse("30-Feb").GetDateTimeFormats();
I learned to use this yesterday (for a different purpose). So try-catch this statement to deal with validity/invalidity of the date :)
"^(([1-9]|0[1-9]|1[0-9]|2[1-9]|3[0-1])[-]([JAN|FEB|MAR|APR|MAY|JUN|JULY|AUG|SEP|OCT|NOV|DEC])[-](d{4}))$"
using System.Text.RegularExpressions
private void fnValidateDateFormat(string strStartDate,string strEndDate)
{
Regex regexDt = new Regex("(^(((([1-9])|([0][1-9])|([1-2][0-9])|(30))\\-([A,a][P,p][R,r]|[J,j][U,u][N,n]|[S,s][E,e][P,p]|[N,n][O,o][V,v]))|((([1-9])|([0][1-9])|([1-2][0-9])|([3][0-1]))\\-([J,j][A,a][N,n]|[M,m][A,a][R,r]|[M,m][A,a][Y,y]|[J,j][U,u][L,l]|[A,a][U,u][G,g]|[O,o][C,c][T,t]|[D,d][E,e][C,c])))\\-[0-9]{4}$)|(^(([1-9])|([0][1-9])|([1][0-9])|([2][0-8]))\\-([F,f][E,e][B,b])\\-[0-9]{2}(([02468][1235679])|([13579][01345789]))$)|(^(([1-9])|([0][1-9])|([1][0-9])|([2][0-9]))\\-([F,f][E,e][B,b])\\-[0-9]{2}(([02468][048])|([13579][26]))$)");
Match mtStartDt = Regex.Match(strStartDate,regexDt.ToString());
Match mtEndDt = Regex.Match(strEndDate,regexDt.ToString());
if (mtStartDt.Success && mtEndDt.Success)
{
//piece of code
}
}
I am using the regular expression of the date for the format "MM/DD/YYYY" like
"^(0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01])[- /.](19|20)\d\d$"
its working fine, no problem....here I want to limit the year between "1950" to "2050", how to do this, can anyone help me....
So the answer depends on how you want to accomplish the task.
Your current Regex search pattern is going to match on most dates in the format "MM/DD/YYYY" in the 20th and 21st century. So one approach is to loop through the resulting matches, which are represented as string values at this point, and parse each string into a DateTime. Then you can do some range validation checking.
(Note: I removed the beginning ^ and ending $ from your original to make my example work)
string input = "This is one date 07/04/1776 and this is another 12/07/1941. Today is 08/10/2019.";
string pattern = "(0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01])[- /.](19|20)\\d\\d";
List<DateTime> list = new List<DateTime>();
foreach (Match match in Regex.Matches(input, pattern))
{
Console.WriteLine(match.Value);
DateTime result;
if (DateTime.TryParse(match.Value, out result))
{
if (result.Year >= 1950 && result.Year <= 2050)
{
list.Add(result);
}
}
}
Console.WriteLine("Number of valid dates: {0}", list.Count);
This code outputs the following, noting that 1776 is not matched, the other two dates are, but only the last one is added to the list.
12/07/1941
08/10/2019
Number of valid dates: 1
Although this approach has some drawbacks, such as looping over the results a second time to try and do the range validation, there are some advantages as well.
The built-in DateTime methods in the framework are easier to deal with, rather than constantly adjusting the Regex search pattern as your acceptable range can move over time.
By range checking afterward, you could also simplify your Regex search pattern to be more inclusive, perhaps even getting all dates.
A simpler Regex search pattern is easier to maintain, and also makes clear the intent of the code. Regex can be confusing and tricky to decipher the meaning, especially for less experienced coders.
Complex Regex search patterns can introduce subtle bugs. Make sure you have good unit tests wrapped around your code.
Of course your other approach is to adjust the Regex search pattern so that you don't have to parse and check afterwards. In most cases this is going to be the best option. Your search pattern is not returning any values that are outside the range, so you don't have to loop or do any additional checking at that point. Just remember those unit tests!
As #skywalker pointed out in his answer, this pattern should work for you.
string pattern = "(0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01])[- /.](19[5-9][0-9]|20[0-4][0-9]|2050)";
year 1950-2050 both inclusive can be found using 19[5-9][0-9]|20[0-4][0-9]|2050
We are using a RegEx Validator to validate an input from a textbox.
The current RegEx expression checks if the current number is between the range of 1 - 999.
We just inherited this code and we need to change the range from 999 to just 365. In short, we need to write a regex to check if the input is between 1 - 365.
Of course, we can just use a RangeValidator or a custom validator. But we don't want to do that because we don't want to introduce a "significant" change.
Thanks!
EDIT:
We should also catch this following patterns:
001 for 1
019 for 19
Using regular expressions is certainly not the best way to validate integer ranges, but here you go:
^([1-9][0-9]?|[12][0-9][0-9]|3[0-5][0-9]|36[0-5])$
[1-9][0-9]? matches 1 - 99
[12][0-9][0-9] matches 100 - 299
3[0-5][0-9] matches 300 - 359
36[0-5] matches 360 - 365
EDIT: With leading zeros (also matches strings like 00000000321):
^0*([1-9][0-9]?|[12][0-9][0-9]|3[0-5][0-9]|36[0-5])$
Mind the gap, ehm leap year. :-)
you really don't want to use regex for that, you should just use /^\d{1,3}$/ and validate the number as being 1..365
as for just regex:
SNIP
ferdinands is fine :)
Little addition to Ferdinand's regexp for catching leading zeros:
^([0]{0,2}[1-9]|[0]?[1-9][0-9]|[12][0-9][0-9]|3[0-5][0-9]|36[0-5])$
[0]{0,2}[1-9] - catches 001, 01, 1...
[0]?[1-9][0-9] - catches 010, 10...
Notice, it does not catch 0234 or 0019