Allow only numbers and letters in an input box or textarea - php

I have s form and I want to make it safe so I want to validate each input value before I save it in my database. For example I have this input field:
<input type="text" name="username" value="" />
and now for example, someone fills it with something other than numbers and letters like
myusername12|\/+*()!#$%^#^&_-+=.,';"
which might be dangerous values. So I want to check first if the field contains only letters and numbers and echo "letters and numbers only" otherwise. How can I do that?

PHP has a handy built in function to perform this test.
http://php.net/manual/en/function.ctype-alnum.php
Check this function returns true before attempting to save the data but make sure you're running DB prep anyway.

How about:
if (preg_match('/^[a-z0-9]+$/', $username) {
echo "Looks good\n";
} else {
echo "Invalid character\n";
}
And, if you want to be unicode compatible:
if (preg_match('/^\p{Xan}+$/', $username) {
echo "Looks good\n";
} else {
echo "Invalid character\n";
}
Where \p{Xan} stands for any alpha-numeric.

Not a complete answer for your problem, but html5 can do this for you:
<input type="text" name="username" pattern="![^a-zA-Z0-9]" title="Only digits and letters" />
If the users blurs the input, it will highlight red (in FF at least). Be aware though, this is clientside. You can use the exaxt same regex in php to validate.
You can also save the regex and use it in both:
$regex = "[a-zA-Z0-9]";
if(isset($_POST['username'])){
echo preg_match('/'.$regex.'/', $_POST['username']) ? 'match' : 'no match';
}
echo '<input name="username" pattern="'.$regex.'" title="Only digits and letters" />';
Small note: I dont know if browsers do complex regexes (or do them differently).

Related

How to stop user from entering only space in input PHP?

I am creating a social site and in the registration code someone can enter only spaces in the input fields.
I don't want them to enter any spaces in the fields except for the password one.
I have tried a bunch of things, empty, trim, htmlentities !trim and some more I forgot. None of them worked. Some of them gave the first name the value of 1.
What am I missing?
Below is a list of things I have tried (not at the same time).
$first_name = trim(strip_tags(filter_var($_POST['first_name'], FILTER_SANITIZE_STRING)));
str_replace(' ', ' ', $first_name);
if (empty($first_name)) {
echo "Fill in first name to sign up";
}
if (!ctype_alnum($first_name)) {
echo "Invalid first name, it only may contain letters or digits";
}
$first_name = $_POST['first_name'] ?? '';
if (empty($first_name)) {
echo "Fill in first name to sign up";
}
if (!ctype_alnum($first_name)) {
echo "Invalid first name, it only may contain letters or digits";
}
$first_name = htmlentities(trim(strip_tags(filter_var($_POST['first_name'], FILTER_SANITIZE_STRING)));
if (empty($first_name)) {
echo "Fill in first name to sign up";
}
if (!ctype_alnum($first_name)) {
echo "Invalid first name, it only may contain letters or digits";
}
Use regular expressions. The following checks it to be at least 5 symbols and contain just letters and digits;
$firstName = trim($_POST['first_name']);
if (!preg_match("/^[a-zA-Z0-9]{5,}$/", $firstName)){
echo 'Invalid';
}
More information on preg_match() can be found here.
Hey i have simple solution regarding your question try one
If you want to submit only text and whitespace than use this one
<input type="text" name="Name" required pattern="[a-zA-Z ]+" >
If you want to submit number and whitespace than use this one
<input type="text" name="Name" required pattern="[0-9 ]+" >
If you want to insert text not whitespace than use this one
<input type="text" name="Name" required pattern="[a-zA-Z]+" >
Use any line according to your requirements no extra line of code or condition simple and secure

How to check if any character has been typed which is not allowed with php

Suppose I have a form and in the form, there is an input field for the users to put their full names. I want only characters (A-Za-z) and spaces to be submitted by the users.
<form action='page2.php'>
<input type='text' name='fullname'>
<input type='submit' name='submit' value='Submit'>
</form>
I know, it can be done by html. But I want to check in page2 if user has typed anything without (A-Za-z) and spaces. How this check can be performed with php?
Try this
if (!preg_match("/^[a-zA-Z]$/", $user)) {
/// not match
}
if you want to use regex then below is the code to check alphabet only
preg_match('/^[a-zA-Z]+$/', $string);
Regex is big for this kind of tasks.
You can use this :
if (ctype_alpha(str_replace(' ', '', $name)) === false) {
$errors[] = 'Name must contain letters and spaces only';
}

how to make a field can not be filled minus or symbol?

So like normal field input, This filed should be filled only by numbers or letters, can not insert like symbol(~!##$/%^&-+=|*.\,) and minus numbers in PHP/html. Can help me please? i done search in internet not found only found for sql or vb
<input type="text" name="text" value="">
where this field will be POST to another php
$name =trim($_POST['name']);
Use this:
bool ctype_alnum ( string $text )
You could use alnum method of respect/validation:
if(v::alnum()->validate($stringToCheck)){
//valid
}
else {
//not valid
}

How to add validation to my form?

I have a php form that is adding information to my sql database, i need it to only accept numbers in the text box.
This is my php form
<form id="MakeBid" action="MakeBid.php" method="POST">
<input type="hidden" name="propertyID" value="1" />
<div>Bid Now
<input type="text" name="pricesoldfor" />
</div>
<input id="submit" input type="submit" value="Submit" />
</form>
Client-side for feedback without loading, you can do something like
<form [...] onsubmit="if( !this.pricesoldfor.match(/\d+/) ) {
alert('Please enter only numbers for the price!'); return false;
}">
(I've written this example inline - as your form will probably be larger, I would advise you not to use the attribute onsubmit and instead attach a proper event handler. Have a look at preventDefault() as well as this is usually a better alternative to return false.)
What you will really need to do is validate in your PHP (server-side) that it is only numbers before you save it to the database. For example like this:
if((string)(int)$input === $input) { /*was a number*/ } else { /*was not a number*/ }
Bear in mind both of these will only allow full numbers (integers), so no "35.43" or similar. Have a look at is_numeric()
You can use javascript for client-side validation. This isnt very secure, but its fast and can be used to provide a responsive user experience, but should always be backed up with server-side validation.
You can use a mix of regular expressions and if/else or case/switch to see what characters have been typed in.
if (!preg_match("/^[0-9]", $textfield))
// display error message
$num = 123456;
if(!filter_var($num, FILTER_VALIDATE_INT))
{
echo("Not number");
}
else
{
echo("Number");
}
visit for all type of validation
http://www.position-relative.net/creation/formValidator/
and demo is below
http://www.position-relative.net/creation/formValidator/demos/demoValidators.html

php validation concept

First of all, I don't want to use any framework but I am looking for a good way to use whitelist validation. I am going to apply it on all the user input I receive, I need validation for XSS protection and I also want to apply different formats for example:
Example 1 XSS.
<input type="text" name="test" value="<script>alert('test');</script" />
Example 2 Date.
<input type="text" name="test" value="31-05-2012" />
Example 3 Time.
<input type="text" name="test" value="15:00" />
Example 4 Max length.
<input type="text" name="test" value="short description" />
Example 5 Min length.
<input type="text" name="test" value="min description" />
Example 6 Alphabetic and default symbols only
<input type="text" name="test" value="hello world. This is à ö text input :P :) :S :$ =D !! ??" />
Example 7 Numeric only
<input type="text" name="test" value="1234567890" />
My idea is to build a clientside and server site validation, if the user gets passed through the clientside validation (jQuery) they will get marked as hacker, since it is impossible for default users to pass through the clientside validation.
My question is: What would be the best way to apply client+serverside validation to prevent XSS and apply regular expressions on fields. Are there any lightweight PHP libraries for validation?
I have looked at:
ctype_alpha
preg_match
But I am not quit sure what would be the best one to use, and ctype_alpha is not allowing default symbols etc.
Any advises? Examples? Thanks for your time and reading, and sorry for the hectic question.
It seems you just need some basic validation, not "whitelist" one.
the idea is quite simple.
Create a server-side validation. with ctype_alpha, preg_match and such. (I hope that your question is not about teaching you these functions from scratch).
Create cleint-side validation if you want, by making AJAX calls to the very same validation routines you've used for the (1).
Of course, you have to use both anyway.
Marking users as a hackers seems not the best idea. What you gonna do with marked users?
I've had a similar problem and ended up writing my own "Input-Datatype" classes. This might be a bit excessive if you only use them for validating input though. But you could build validation functions that use a mix of PHP functions such as preg_match, is_numeric, strtotime etc...
An example for date validation would be:
public function validate(&$value) {
$date = strtotime($value);
if($date === false){
//Error no valid date
}else{
if(isset($this->maxDate)){
if($date>strtotime($this->maxDate)){ //maxDate being the maximal date allowed
//Error max date exceeded
}
}
if(isset($this->minDate)){
if($date<strtotime($this->minDate)){ //minDate being the minimal date allowed
//Error date too low
}
}
$value = strftime($this->format,$date); //format being the format in which the date should be saved
}
Another example for validating text could be:
public function validate(&$value) {
if (isset($value) && $value != "") {
if(isset($this->maxLength)&&$this->maxLength!= ""){ //maxLength being the maximal number of characters
if (strlen($value) > $this->maxLength) {
//Error max length exceeded
}
}
} else {
if (!$this->allowNull) { //allowNull being a boolean: true if text can be empty
//Error value is empty
}
}
if(isset($this->regex)&&$this->regex!= ""){ //regex can be any regular expression, e.g: /[A-Za-z]/ for letters only
if(!preg_match($this->regex, $value)){
//Error value does not match expression
}
}
}
As far as XSS goes, make sure you use prepared statements when interacting with a database and use htmlentities when displaying user inputted data.
Hope this helps.
Some time ago, i've written a lightweight-validation class. Maybe you can use it.
For example:
$oValidator = new Validator();
$oValidator->setLanguage('en');
$oValidator->isValid('short description', 'max_length[4]');
echo $oValidator->getLastErrorMessage();
//The input can not exceed 4 characters in length.
$oValidator->isValid('min description', 'min_length[5]');
$oValidator->isValid('hello world. This is à ö text input :P :) :S :$ =D !! ??', 'min_length[5]');
$oValidator->isValid('1234567890', 'digits');
Rule definition:
/**
* #ErrorMessage[lang=de] Die Eingabe muss mindestens %d Zeichen lang sein.
* #ErrorMessage[lang=en] The input must be at least %d characters in length.
*/
public function check_min_length($mValue, $aParams)
{
return (strlen($mValue) >= $aParams[0]);
}
Example:
http://sklueh.de/2013/01/lightweight-php-validator-neue-version/
github:
https://github.com/sklueh/Lightweight-PHP-Validator

Categories