Validate that input string does not exceed word limit
Maybe str_word_count
could help
http://php.net/manual/en/function.str-word-count.php
$Tag = 'My Name is Gaurav';
$word = str_word_count($Tag);
echo $word;
php - How can I check if the sentence consists of a single word?
you can use
$result = explode(' ', trim("barcelona "));
print_r($result);
trim will remove all white space at the beginning and the end of your string
How to set min and max character length in a textbox using javascript
You could do something like this:
`
function checkLength(){
var textbox = document.getElementById("textbox");
if(textbox.value.length <= 10 && textbox.value.length >= 5){
alert("success");
}
else{
alert("make sure the input is between 5-10 characters long")
}
}
</script>
<input type="text" id="textbox"></input>
<input type="submit" name="textboxSubmit" onclick="checkLength()" />
`
Limiting Python input strings to certain characters and lengths
Question 1: Restrict to certain characters
You are right, this is easy to solve with regular expressions:
import re
input_str = raw_input("Please provide some info: ")
if not re.match("^[a-z]*$", input_str):
print "Error! Only letters a-z allowed!"
sys.exit()
Question 2: Restrict to certain length
As Tim mentioned correctly, you can do this by adapting the regular expression in the first example to only allow a certain number of letters. You can also manually check the length like this:
input_str = raw_input("Please provide some info: ")
if len(input_str) > 15:
print "Error! Only 15 characters allowed!"
sys.exit()
Or both in one:
import re
input_str = raw_input("Please provide some info: ")
if not re.match("^[a-z]*$", input_str):
print "Error! Only letters a-z allowed!"
sys.exit()
elif len(input_str) > 15:
print "Error! Only 15 characters allowed!"
sys.exit()
print "Your input was:", input_str
Asking the user for input until they give a valid response
The simplest way to accomplish this is to put the input
method in a while loop. Use continue
when you get bad input, and break
out of the loop when you're satisfied.
When Your Input Might Raise an Exception
Use try
and except
to detect when the user enters data that can't be parsed.
while True:
try:
# Note: Python 2.x users should use raw_input, the equivalent of 3.x's input
age = int(input("Please enter your age: "))
except ValueError:
print("Sorry, I didn't understand that.")
#better try again... Return to the start of the loop
continue
else:
#age was successfully parsed!
#we're ready to exit the loop.
break
if age >= 18:
print("You are able to vote in the United States!")
else:
print("You are not able to vote in the United States.")
Implementing Your Own Validation Rules
If you want to reject values that Python can successfully parse, you can add your own validation logic.
while True:
data = input("Please enter a loud message (must be all caps): ")
if not data.isupper():
print("Sorry, your response was not loud enough.")
continue
else:
#we're happy with the value given.
#we're ready to exit the loop.
break
while True:
data = input("Pick an answer from A to D:")
if data.lower() not in ('a', 'b', 'c', 'd'):
print("Not an appropriate choice.")
else:
break
Combining Exception Handling and Custom Validation
Both of the above techniques can be combined into one loop.
while True:
try:
age = int(input("Please enter your age: "))
except ValueError:
print("Sorry, I didn't understand that.")
continue
if age < 0:
print("Sorry, your response must not be negative.")
continue
else:
#age was successfully parsed, and we're happy with its value.
#we're ready to exit the loop.
break
if age >= 18:
print("You are able to vote in the United States!")
else:
print("You are not able to vote in the United States.")
Encapsulating it All in a Function
If you need to ask your user for a lot of different values, it might be useful to put this code in a function, so you don't have to retype it every time.
def get_non_negative_int(prompt):
while True:
try:
value = int(input(prompt))
except ValueError:
print("Sorry, I didn't understand that.")
continue
if value < 0:
print("Sorry, your response must not be negative.")
continue
else:
break
return value
age = get_non_negative_int("Please enter your age: ")
kids = get_non_negative_int("Please enter the number of children you have: ")
salary = get_non_negative_int("Please enter your yearly earnings, in dollars: ")
Putting It All Together
You can extend this idea to make a very generic input function:
def sanitised_input(prompt, type_=None, min_=None, max_=None, range_=None):
if min_ is not None and max_ is not None and max_ < min_:
raise ValueError("min_ must be less than or equal to max_.")
while True:
ui = input(prompt)
if type_ is not None:
try:
ui = type_(ui)
except ValueError:
print("Input type must be {0}.".format(type_.__name__))
continue
if max_ is not None and ui > max_:
print("Input must be less than or equal to {0}.".format(max_))
elif min_ is not None and ui < min_:
print("Input must be greater than or equal to {0}.".format(min_))
elif range_ is not None and ui not in range_:
if isinstance(range_, range):
template = "Input must be between {0.start} and {0.stop}."
print(template.format(range_))
else:
template = "Input must be {0}."
if len(range_) == 1:
print(template.format(*range_))
else:
expected = " or ".join((
", ".join(str(x) for x in range_[:-1]),
str(range_[-1])
))
print(template.format(expected))
else:
return ui
With usage such as:
age = sanitised_input("Enter your age: ", int, 1, 101)
answer = sanitised_input("Enter your answer: ", str.lower, range_=('a', 'b', 'c', 'd'))
Common Pitfalls, and Why you Should Avoid Them
The Redundant Use of Redundant input
Statements
This method works but is generally considered poor style:
data = input("Please enter a loud message (must be all caps): ")
while not data.isupper():
print("Sorry, your response was not loud enough.")
data = input("Please enter a loud message (must be all caps): ")
It might look attractive initially because it's shorter than the while True
method, but it violates the Don't Repeat Yourself principle of software development. This increases the likelihood of bugs in your system. What if you want to backport to 2.7 by changing input
to raw_input
, but accidentally change only the first input
above? It's a SyntaxError
just waiting to happen.
Recursion Will Blow Your Stack
If you've just learned about recursion, you might be tempted to use it in get_non_negative_int
so you can dispose of the while loop.
def get_non_negative_int(prompt):
try:
value = int(input(prompt))
except ValueError:
print("Sorry, I didn't understand that.")
return get_non_negative_int(prompt)
if value < 0:
print("Sorry, your response must not be negative.")
return get_non_negative_int(prompt)
else:
return value
This appears to work fine most of the time, but if the user enters invalid data enough times, the script will terminate with a RuntimeError: maximum recursion depth exceeded
. You may think "no fool would make 1000 mistakes in a row", but you're underestimating the ingenuity of fools!
Related Topics
PHP Foreach() with Arrays Within Arrays
How to Validate Non-English (Utf-8) Encoded Email Address in JavaScript and PHP
Appending a Value of a Variable to a Variable Name
Using PHP, How to Insert Text Without Overwriting to the Beginning of a Text File
Setting $_Session Doesn't Work on Localhost Using Xampp
From the String Name of a Class, How to Get a Static Variable
Class App\Http\Controllers\Usercontroller Does Not Exist
Why Does 'Intval(19.9 * 100)' Equal '1989'
PHP - Is "Include" Function Secure
How to Password Protect Streaming Videos with PHP
Twig Problem with PHP 7.4 in Write Variable
Wordpress, Nginx Proxy and Subdirectory: Wp-Login.PHP Redirects to Domain
How to Launch a PHP Script at Apache Startup
How to Get Order Id in Woocommerce_Email_Headers Hook
Get a Single Row from the Database Using Ajax in Codeigniter
In Laravel 5, How to Disable Verifycsrftoken Middleware for Specific Route