YOUR ARGUMENT IS INVALID, isn’t it?

--Originally published at Coding The Future

via GIPHY

If you had been in my house while I was watching the US Presidential Debates you would probably had heard me scream to my computer "YOUR ARGUMENT IS INVALID DONALD!". Not only do I hate that guy for being so racist, but also because everything he says is just so dumb. And then my girl Hillary comes in saying that you can fact-check Donald from her website in real time. Gotta love that QUEEN!

But aside from US politics, let's move on to today's topic: validating user input. This will not exactly help us to fact-check Donald, but to make sure that the user is entering the right kind of information.

Let's take a registration form for example. We want to collect the user's name, email, and phone number. Therefore, we must make sure that the user includes an @ and a .something and that only numbers are inputted in the phone number field. Here's how it works...

Using the "Try" Approach

To validate input, we could use if-statements, but there's a more effective approach commonly known as Try-catch. This method tries to do something, and if it can't, instead of crashing the program, makes it do something else.

Take a look at the following sample code:

try: phoneNum = int(input("Please enter your phone #: ")) except ValueError: print("Sorry, that phone number is not valid.")

As you can see, the first step was to type try followed by the code you need to validate, which in this case is making sure the input only whole numbers, and then using an except statement to break out of if an error was returned. This prevents the program from crashing, and if combined with a while loop, can prompt the user to enter their number again until they get right.

Validating email

Email validation can be a little harder, but a little easier at the same time. This is because the easiest way to do so is using a library called validate_email that can be installed from your terminal.

Once installed, it is super easy to use. All you need to do is call the validate_email() function.

is_valid = validate_email('example@example.com')

The setup instructions for this module can be found here.

That's it for now... And get exited, because I will be talking about my first Twitter Bot and how to build your own next week!

@emamex98

comments powered by Disqus