Click here to Skip to main content
15,904,415 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
i want to validated birthday where if user choose the date today the system will prompt an error message " invalid birthday"

What I have tried:

Dim SelectedDate As Date = dtbday.Text
If SelectedDate.ToShortDateString = Date.Today Then
MessageBox.Show("The selected date is not a valid birthday", "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
else
.....
Posted
Updated 3-Aug-17 4:06am
Comments
Richard MacCutchan 3-Aug-17 10:35am    
Use a DatePicker, not a TextBox to allow date inputs. So you can guarantee that it will at least be a valid date, even if it does not meet the limits of your application. Although you can enforce certain limits on the DatePicker object.

dtbday.Text will return a String, which could contain anything. There's no guarantee that it can be converted to a Date. Use Date.TryParse[^] to attempt to convert it to a date, and warn the user if it can't be converted.

If it can be converted, you'll want to make sure the date is not in the future. If you have other requirements for a valid birthday, then you'll need to add them as well.
VB.NET
Dim SelectedDate As Date
If Not Date.TryParse(dtbday.Text, SelectedDate) Then
    MessageBox.Show("The entered text is not a valid date", "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
    
ElseIf SelectedDate.Date > DateTime.Today Then
    MessageBox.Show("Your date of birth cannot be in the future", "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
    
End If
 
Share this answer
 
Comments
Member 13343055 3-Aug-17 10:36am    
it works! thanks mate! you saved me two times already :)
Member 13343055 3-Aug-17 11:54am    
follow up question. please help. im getting this error with your given code.
Conversion from string "" to type date is invalid.
what should i do?
Richard Deeming 3-Aug-17 11:56am    
On which line?
Member 13343055 3-Aug-17 12:02pm    
ahm. i dont know. im getting this error when i hit the save button..
maybe it's because of .text that i used?
Richard Deeming 3-Aug-17 12:06pm    
Well, debug your code and find out which line is throwing the exception.

As far as I can see, none of the code I've posted would throw that error. So unless there's something odd happening in the Text property accessor, I can't see what would cause it.
ToShortDateString will format it in a display friendly format depending on your localisation.

You should do the comparison the date.

Try this.

If SelectedDate = Date.Today
 
Share this answer
 
Comments
Member 13343055 3-Aug-17 9:26am    
it doesn't work

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