问题
I have an input field that needs a username. The scenario is, how can i prevent user from providing whitespace or whitespaces in the that field? I already added required
in the input field so i can prevent user from leaving it blank.
<input type="text" name="username" required>
but what if the user puts whitespace or as many whitespace as he can, is there any possible way i can detect this and throw error to the user?
in my php file i already have
if(empty($_POST['username'])){
echo "Username should not be empty!";
}
but this will fail because of the whitespaces the users put in the input field.
回答1:
You could do like this.
if(isset($_POST['username']))
{
if(strlen(trim($_POST['username']))<=0){
echo "Username should not be empty!";
}
}
回答2:
You can use trim and strlen php functions
回答3:
Try This....
if( trim($_POST['username']) == ""){
echo "Username should not be empty!";
}
回答4:
u can use $.trim() jquery function before to submit form.
var nowhitespace = $.trim($("#input").val());
回答5:
I think str_replace()
is all you want. Or you could some javascript to prevent whitespace from being entered into the input field.
<?php
$s = str_replace(' ', '', $_POST['username']);
?>
If you're going to use trim()
, don't forget about rtrim()
来源:https://stackoverflow.com/questions/21709682/how-to-check-if-data-is-empty-or-whitespace-only-in-php