PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Saturday, July 30, 2022

[FIXED] How to raise customizable ValueError for input containing two dates?

 July 30, 2022     input, python, python-3.x, validation, valueerror     No comments   

Issue

I am trying to understand raising an exception little better.Below is python code, as you can see I am asking for two date inputs from user. If user types "2022" and hit enter it is returning python ValueError with msg "Not enough values to unpack (expected 2, got 1)". Instead what I would like to do is if user types year,month or date then instead of python default ValueError. It should raise an Error saying "Incorrect date entered, please enter dates in YYYY-MM-DD format ONLY" and should display the input box again for user to enter correct date. My question is how to raise customizable ValueError and ask the user to renter the dates?

Any help will be appreciated!

Code

def validate(date_text):
        try:
            for y in date_text:
                if not datetime.datetime.strptime(date_text, '%Y-%m-%d'):
                    raise ValueError
                else:
                    return True
        except ValueError:
            print("Incorrect date format, please enter dates in YYYY-MM-DD format ONLY")
            return False
while True:
    start_date,end_date= input("Enter employee start and termination date separated by (,)  in YYYY-MM-DD format only: ").split(",")
    if validate(start_date) and validate(end_date):
        break

Solution

I was able to resolve my issue using below code. Basically, I needed another try & except block in while statement. Thanks @Иван Балван for feedback!

def validate(date_text):
        try:
            datetime.datetime.strptime(date_text, '%Y-%m-%d')
            return True
        except ValueError:
            print("Incorrect date format, please enter dates in YYYY-MM-DD format ONLY")
            return False

while True:
    try:
        start_date,end_date= input("Enter employee start and termination date separated by (,)  in YYYY-MM-DD format only: ").split(",")
        if validate(start_date) and validate(end_date):
            break
    except ValueError:
        print("Incorrect date enetered, please enter both dates in YYYY-MM-DD format ONLY")


Answered By - biggboss2019
Answer Checked By - David Goodson (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing