Click here to Skip to main content
15,887,979 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
while validating date of birth,if the month contains string or character,int32.tryparse returns false,which should be true and the code moves to else part.

I want the user to use DD MM YYYY format and numeric like 12 02 2014.For testing.I entered a string in the month field but it is not throwing error.My input was 12 sx 2014.

Can someone shed some light on this.

if (dobMonth.Text == String.Empty || !Int32.TryParse(dobMonth.Text, out intParsed))
{
valid = false;
dobMonth.CssClass = "error";
ErrDOB.Visible = true;
}
else
{
}

<div><label>Date of Birth:<span class="req-field">*</span></label></div>

<div><span><asp:TextBox ID="txtDOBDay" Text="DD" MaxLength="2" runat="server" /></span></div>

<div><span><asp:TextBox ID="txtDOBMonth" Text="MM" MaxLength="2" runat="server" /></span></div>                              
<div><span><asp:TextBox ID="txtDOBYear" Text="YYYY" MaxLength="4"       runat="server" /></span></div>
Posted
Updated 1-Jan-15 19:06pm
v4
Comments
George Jonsson 2-Jan-15 1:15am    
TryParse is not supposed to throw an error, even if the input is badly formatted, it will just return false.
I would go for Solution 2, and use DateTime.Parse.

Notice a mismatch of ID: dobMonth vs txtDOBMonth.
You may want to use DateTime.TryParseExact Method[^] instead.
 
Share this answer
 
Int32.TryParse will try to convert the ENTIRE string to an integer. What you're claiming as your input, "12 sx 1024", in not a valid integer so TryParse returns false.
 
Share this answer
 

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