Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 3 of 3
  1. #1
    Regular Coder
    Join Date
    Sep 2007
    Posts
    125
    Thanks
    30
    Thanked 0 Times in 0 Posts

    Easy "regular expression" question/solution...

    I'm sorry to bother people here with this, but I'm SOOOO bad with Regular Expressions. I just need a simple one to check if the data entered into a text field is in the date format YYYY-MM-DD. So, I'd need to check:

    ####-##-##

    If anyone could help me finish the code below, I'd really appreciate it!:
    Code:
    if ($_POST) {
      // ERROR CHECKING
      if ($_POST['due_date'] DOES NOT MATCH THE YYYY-MM-DD FORMAT) {
      	$error = 'Please make sure that your date is in the format YYYY-MM-DD';
      }
    }

  • #2
    Regular Coder
    Join Date
    Apr 2003
    Location
    Montreal, QC
    Posts
    340
    Thanks
    3
    Thanked 2 Times in 2 Posts
    This should work. It goes a little further checking that the YYYY is between 1000 and 2999, (restricts the first character to a 1 or 2), also, for the day it restricts the first character to a 0, 1, 2, or 3.

    To only make sure that it's ####-##-## you could change the $date_pattern variable to:
    Code:
    $date_patterh = '/[0-9]{4}-[0-9]{2}-[0-9]{2}/'
    PHP Code:
    if ($_POST) {
      
    // ERROR CHECKING
    $date_pattern '/[12][0-9]{3}-[01][09]-[0-3][0-9]/'
      
    if (!preg_match($date_pattern,$_POST['due_date'])) {
          
    $error 'Please make sure that your date is in the format YYYY-MM-DD';
      }

    I learned regular expressions from the tutorial at http://www.regular-expressions.info - they're not as scary as you think before you start learning them!
    Search for Laughter or Just Search?
    GiggleSearch.org
    Blog: www.johnbeales.com
    All About Ballet: www.the-ballet.com

  • Users who have thanked johnnyb for this post:

    ShootingBlanks (11-16-2007)

  • #3
    Regular Coder
    Join Date
    Sep 2007
    Posts
    125
    Thanks
    30
    Thanked 0 Times in 0 Posts
    Works great - thanks!!!


  •  

    Posting Permissions

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