Name length validation in php

Name length validation in php

In this article, we will show how you can perform string length validation in a web form with PHP.

First, what is string length validation and why is it important?

String length validation is measuring the length of a string entered into a text box and making sure that it doesn't go under the minimum length or that it doesn't exceed the maximum length. It is important because let's say, for example, you have members sign up on your website, you may want to limit the length of the username and password a user can have. Having a member sign up with a username or password of 1 or 2 or 3 characters is too short, and could present a security issue. More than likely, we want the username and password to be at least 6 characters in length but not more than, say, 20 characters, because we don't want them to be too long.

Look at the example below.

The username and password must be between 6 and 15 characters. Below this, it will tell the user that the username or password is too short. Above this limit, it will tell you that the username or password is too long.


So how do we create this form above and provide output back if the username is too short or too long?

Coding


HTML Code

The HTML code to create the form above, the 2 text boxes and the 'Enter' button, is:

This HTML code creates the username and password text boxes, as well as the 'Enter' button.

PHP Code

The PHP code to retrieve the user-entered information, measures the length of the strings, and then outputs the appropriate feedback to the user, so that he can know if he's making any mistakes:

The $username and $password variables retrieve and store the values of the information the user has entered into the username textbox and the password textbox. The $enterbutton retrieves the information from the 'Enter' button. Through this variable, we can determine if the 'Enter' button has been clicked or not.

The $usernamelength variable stores the value of the length of the string of the username and the $passwordlength variable stores the length of the password.

In the first if statement, if (isset($enterbutton)){, we do the following functions only if the 'Enter' button has been clicked. The remaining if statements check to determine if the length of the username and password are below 6 or above 15 characters. If they are, the appropriate message is output to the user. If the username and password are between 6 and 15 characters, then no message is output to the user, because the user correctly chose a username and password.

This is how most web forms handle validation. They output red text usually to a user, only if a form field has been incorrectly filled out. If not, there are no messages.

Notice that the output statements have around them. In the CSS code, this tag makes the text red, standing out more to alert the user that the form has been incorrectly filled out.

Is there a function to check if a string is too long or too short, I normally end up writing something like this in several places:

if (strlen($input) < 12)
{
   echo "Input is too short, minimum is 12 characters (20 max).";
}
elseif(strlen($input) > 20)
{
   echo "Input is too long, maximum is 20 characters.";
}

I know you can easily write one but is there one built into PHP?

I normally collect errors as I validate input, so the above code would be written:

$errors = array();

    if (strlen($input) < 12)
    {
       $errors['field_name'] = "Field Name is too short, minimum is 12 characters (20 max).";
    }
    elseif(strlen($input) > 20)
    {
       $errors['field_name'] = "Field Name is too long, maximum is 20 characters.";
    }

How can that be made into a function ^?

asked Mar 31, 2011 at 19:29

2

I guess you can make a function like this:

function validStrLen($str, $min, $max){
    $len = strlen($str);
    if($len < $min){
        return "Field Name is too short, minimum is $min characters ($max max)";
    }
    elseif($len > $max){
        return "Field Name is too long, maximum is $max characters ($min min).";
    }
    return TRUE;
}

Then you can do something like this:

$errors['field_name'] = validStrLen($field, 12, 20);

joanis

8,22112 gold badges26 silver badges36 bronze badges

answered Mar 31, 2011 at 19:34

gen_Ericgen_Eric

217k40 gold badges295 silver badges334 bronze badges

PHP validate minimum and maximum integer number you can use this:

$quantity = 2;
if (filter_var($quantity, FILTER_VALIDATE_INT, array("options" => array("min_range"=>1, "max_range"=>10))) === false) {
    echo("Quantity is not within the legal range");
} else {
    echo("Quantity is within the legal range");
}

answered Oct 5, 2017 at 17:18

Name length validation in php

Muhammad ShahzadMuhammad Shahzad

8,87021 gold badges80 silver badges128 bronze badges

0

How about something like:

$GLOBALS['errors'] = array();

function addError($msg) {
    $GLOBALS['errors'][] = $msg;
}

function printErrors() {
    foreach ($GLOBALS['errors'] as $err)
        echo "$err\n";
}

Just call addError('error message here') as many times as you need, followed by a printErrors() call at the end.

answered Mar 31, 2011 at 19:34

UnsignedUnsigned

9,3514 gold badges45 silver badges68 bronze badges

you can make a error function that utilizes session vars:

//at the top of the file:
session_start();
//....code
error("Field Name is too short, minimum is 12 characters (20 max).");
//.. some code
//at the end of the file:
displayErrors();

function error($msg){
   if(!isset($_SESSION['errors'])) $_SESSION['errors'] = array();
   $_SESSION['errors'][] = $msg;
}

function displayErrors(){
     foreach($_SESSION['errors'] as $err){
         echo $err.'
'.PHP_EOL; } unset($_SESSION['errors']); }

Demo here: http://codepad.org/TKigVlCj

answered Mar 31, 2011 at 19:35

NaftaliNaftali

143k39 gold badges240 silver badges299 bronze badges

/* Helper function */
function validateLength($value, $minLength, $maxLength, $fieldTitle) {
    $valueStrLen = strlen($value);

    if ($valueStrLen < $minLength) {
        return "$fieldTitle is too short, minimum is $minLength characters ($maxLength max).";
    } elseif($valueStrLen > $maxLength) {
        return "$fieldTitle is too long, maximum is $maxLength characters.";
    } else {
        return '';
    }   
}

/* Example of usage */

$errors = array();

if ( $err = validateLength($_GET['user_name'], 12, 20, 'User name') ) {
    $errros['user_name'] = $err;
}

if ( $err = validateLength($_GET['user_pass'], 12, 20, 'Password') ) {
    $errros['user_pass'] = $err;
}

answered Mar 31, 2011 at 19:45

function validateLenght($s, $min, $max) {
    if (strlen($s) > $max) { return 2; }
    elseif (strlen($s) < $min) { return 1; }
    else { return 0; }
}

if (validateLenght('test', 5, 20) > 0) {
    echo 'Username must be between 5 and 20 characters.';
}

answered Apr 20, 2014 at 15:26

Brynner FerreiraBrynner Ferreira

1,4971 gold badge21 silver badges20 bronze badges

How about this:

if(((strlen($input)<12)||(strlen($input) > 20)))
    {
        $errors['field_name'] = "Must be 12-20 characters only. Please try again.";         
    }

answered Mar 24, 2021 at 9:52

Name length validation in php

1

How can I validate a name in PHP?

PHP validates the data at the server-side, which is submitted by HTML form. You need to validate a few things: Empty String..
$name = $_POST ["Name"];.
if (! preg_match ("/^[a-zA-z]*$/", $name) ) {.
$ErrMsg = "Only alphabets and whitespace are allowed.";.
echo $ErrMsg;.
} else {.
echo $name;.

How do you find the length of a string in PHP?

The strlen() is a built-in function in PHP which returns the length of a given string. It takes a string as a parameter and returns its length. It calculates the length of the string including all the whitespaces and special characters.

How do I limit characters in PHP?

php limit string to 50 characters – You can limit string to N number with PHP built-in function. Use wordwrap() to truncate the string without breaking words if the string is longer than 50 characters.

What is the use of strlen () function in PHP?

The strlen() function returns the length of a string.