Click here to Skip to main content
15,885,366 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
How Do I Do Validation For Date


SQL
[Required(ErrorMessage = "Select Date Of Birth")]
[RegularExpression(@"^([1|2]{1}[0|9]{1}[0-9]{1}[0-9]{1})[\-](0?[1-9]|1[012])[\-](0?[1-9]|[12][0-9]|3[01])+$ ", ErrorMessage = "Enter YYYY-MM-DD format only")]
public Nullable<System.DateTime> DOB { get; set; }


and in rest client i am passing

VB
FName: "ADONIS",
LName: "STEVENSON",
Record: "22-11",
DOB: "1983-07-22",

still i am getting same error message that

CSS
{
Message: "The request is invalid."
ModelState: {
tblFighters.DOB: [1]
0:  "Enter YYYY-MM-DD format only"
-
}-
}

after passing same format i am getting an error
Posted
Updated 19-Aug-15 10:56am
v2
Comments
Sinisa Hajnal 19-Aug-15 4:30am    
Is your regex working when you try it in some regex tester?
phil.o 19-Aug-15 4:52am    
Regular expressions are not suitable - at all - for date input validations. There are many cases where the input would match the expression, without being a valid DateTime (example: 2015-02-31).
Daksh7 19-Aug-15 5:14am    
if you have any regex for yyyy-mm-dd format then please let me know
phil.o 19-Aug-15 5:16am    
Hum ^^
Read carefully my statement: Regular expressions are not suitable - at all - for date input validations.
So, sorry, but I don't have that regular expression; trying to do that would be like trying to drive a nail with a screwdriver.
Maciej Los 19-Aug-15 16:56pm    
Do not repost!!!

Phil.o is absolutely right. You must not go for regex(it's vulnerable). Why don't you go for any custom attribute based validation. Hope this link helps

https://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.customvalidationattribute%28v=vs.95%29.aspx
 
Share this answer
 

I would use the DateTime class to do the validation


C#
string requiredFormat = "yyyy-MM-dd";
string dateString = "1999-04-08";
DateTime dateTime;
Console.WriteLine(
    DateTime.TryParseExact(dateString, requiredFormat, null, DateTimeStyles.None, out dateTime)
        ? "string is valid "
        : "string is not  valid ");
 
Share this answer
 
v2
Comments
Matthew Dennis 19-Aug-15 17:30pm    
Don't you mean string requiredFormat = "yyyy-MM-dd";?
George Swan 19-Aug-15 17:57pm    
You are quite right. I copied the format from the question. 'mm' is minutes so 'yyyy-mm-dd' would allow 1999-59-02. Thanks

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900