To Allow Only String and Numbers Using PHP, we use PHP in-built functions. We do it with textbox input. Where the user gives some input on the textbox then using PHP inbuilt function we validate the staring or number using PHP.
Here are 2 thing we discuss about,
- Allow only characters in textbox using PHP.
- Allow only numbers in textbox using PHP.
Allow only characters in textbox using PHP
ctype_alpha
: ctype_alpha() is PHP inbuilt function that can validate the user input is a string or any character or not. This also takes the spaces between characters as non-character.
Example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
<?php session_start(); if(isset($_POST['submitBtn'])){ $string = $_POST['user_input']; $_SESSION['user_input'] = $_POST['user_input']; if (ctype_alpha ($string)) { echo "All Strings!"; } else { echo "Something's Wrong"; } } ?> <form method="post"> <p><input type="text" name="user_input" value="<?php echo isset($_SESSION['user_input']) ? $_SESSION['user_input'] : ''; ?>"></p> <p><input type="submit" name="submitBtn" value="check"></p> </form> |
Here we use PHP session to maintain the textbox value after page reload.
Output:
Allow only numbers in textbox using PHP
ctype_digit
: ctype_digit() is also a PHP inbuilt function which validates only digit or numbers entered by the user. This is also doesn’t take any spaces on the textbox.
Example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
<?php session_start(); if(isset($_POST['submitBtn'])){ $number = $_POST['user_input']; $_SESSION['user_input'] = $_POST['user_input']; if (ctype_digit($number)) { echo "All are numbers!"; } else { echo "Something's Wrong"; } } ?> <form method="post"> <p><input type="text" name="user_input" value="<?php echo isset($_SESSION['user_input']) ? $_SESSION['user_input'] : ''; ?>"></p> <p><input type="submit" name="submitBtn" value="check"></p> </form> |
On the above code we also manage the value after page is reloaded by using PHP session.
Output:
How to Test
Copy complete code and create a PHP file then paste the code.
You can also use localhost to test. You can check the out also on above.
If you want to know more about those function, you can check on PHP official site here: https://www.php.net/manual/en/ref.ctype.php
Also Check:
- Get List of Holidays Using Google Calendar API
- 2 Ways To Check if Email already exists Using PHP
- How to Keep Value After Page Reload in PHP
- Migrate WordPress Site To New Host Manually
Happy Coding..!
3 Replies to “Allow Only String and Numbers Using PHP”