Question

I have a LINQ query

rpt = base.Session.QueryOver<Report>(() => rptAlias).
                                  JoinAlias(() => rptAlias.ReportStatus, () => statusAlias).
                                  JoinAlias(() => rptAlias.Patient, () => patAlias).Left.JoinAlias(() => rptAlias.SoapNotes, () => soapAlias).
                                  JoinAlias(() => patAlias.User, () => usrAlias).Where
                                  (() => (usrAlias.FirstName.IsLike(data, MatchMode.Anywhere)
                                  || usrAlias.LastName.IsLike(data, MatchMode.Anywhere) || usrAlias.Email.IsLike(data, MatchMode.Anywhere) || (patAlias.DateOfBirth.Date)==(Convert.ToDateTime(data)) ||
                                 (patAlias.MedNexusId.IsLike(data, MatchMode.Anywhere) || patAlias.MedNexusId == null)) && usrAlias.IsDeleted == false
                                  && rptAlias.IsDeleted == false && rptAlias.IsNormal.IsIn(lstIsNormal)
                                  && statusAlias.Id.IsIn(lstSearch)
                                  )
                                  .OrderBy(() => usrAlias.LastName).Desc.OrderBy(() => rptAlias.Id).Asc
                                 .Skip(pageNumber * pageSize)
                                 .Take(pageSize)
                                 .List<Report>();

here u must have noticed a variable data,now the problem is it contains whatever we enter in a text box in the view so it may contain 1.First Name 2.Last Name 3.Id 4.Email Id 5.Date of birth

or the worst case is it can be null as well so when it contains date of birth then all is well but in other cases the data is not in proper format to be passed as a parameter to Convert.ToDateTime and i get exception.

So my question is How can I check beforehand that data is in correct format or not?

Was it helpful?

Solution 2

Try this :

    DateTime myDt;
    bool parsed = DateTime.TryParseExact(date,"d/M/yyyy",null,out myDt);
    if(parsed) DoSomething;

Actually DateTime.TryParseExact works on taking a Date template which u see here as "d/M/yyyy" and try to match the string to be exact like that "12/03/1902" for example . Find more here : http://msdn.microsoft.com/en-us/library/ms131044(v=vs.110).aspx

Also You can use DateTime.TryParse

OTHER TIPS

You should use DateTime.TryParse .

You will need to parse the string before creating the query, which is A Good Thing - make sure your input is correct first, then process it.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top