Results 1 to 3 of 3

Thread: [2.0] Validating a string for MM/DD/YYYY format

  1. #1

    Thread Starter
    Hyperactive Member
    Join Date
    Oct 2003
    Posts
    436

    [2.0] Validating a string for MM/DD/YYYY format

    Howdy folks,

    I have a string variable that should have data in it as 06/12/2007 (MM/DD/YYYY). basically a date. how can I validate if it is in the correct format. If the string variable has data in any other format say 06/12/07 (MM/DD/YY), it should throw an error.

    How can I do that in C#?
    thanks
    nath

  2. #2
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    111,221

    Re: [2.0] Validating a string for MM/DD/YYYY format

    You have two choices. DateTime.TryParseExact will parse the string and return False if it fails, while ParseExact will throw an exception.
    Why is my data not saved to my database? | MSDN Data Walkthroughs
    VBForums Database Development FAQ
    My CodeBank Submissions: VB | C#
    My Blog: Data Among Multiple Forms (3 parts)
    Beginner Tutorials: VB | C# | SQL

  3. #3
    Arabic Poster ComputerJy's Avatar
    Join Date
    Nov 2005
    Location
    Happily misplaced
    Posts
    2,513

    Re: [2.0] Validating a string for MM/DD/YYYY format

    You can also use regular expressions:
    Code:
            private bool IsFormattedDate(string Expression)
            {
                return System.Text.RegularExpressions.Regex.IsMatch("" , @"(?<Month>([1-9])|(0[1-9])|(1[0-2]))/(?<Day>\d{2})/(?<Year>(?:\d{4}))(?x)");
            }
    "I'm not normally a praying man, but if you're up there, save me... Superman!" - Homer Simpson
    My Blog

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width