Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How set requirements for text input field (html/php) ?

In my php script i have this input field.

   <input type="text" name="try" size="10" id="try" maxlength="5" >

What is the easy way to make i require 5 characters and show an error message if they are not only letters.

like image 426
Axxess Avatar asked Feb 19 '23 01:02

Axxess


2 Answers

With HTML5 you can use the pattern attribute:

<input type="text" name="try" size="10" pattern="[A-Za-z]{5}" title="5 alphabetic characters exactly">

This will allow exactly 5 characters, which can only be uppercase or lowercase alphabetic characters.

like image 144
Justin Lewis Avatar answered Feb 22 '23 22:02

Justin Lewis


You can probably do that in jQuery on the client side. You will also need to do it on the server side, since JavaScript can (and will) be bypassed by an attack vector. A regular expression like this will do the server-side validation in PHP.

$rgx = '/[A-Z]{5,}/i';

Combining the approach...

http://www.laprbass.com/RAY_temp_axxess.php?q=abcde
http://www.laprbass.com/RAY_temp_axxess.php?q=ab
http://www.laprbass.com/RAY_temp_axxess.php?q=abcdefg

<?php // RAY_temp_axxess.php
error_reporting(E_ALL);

// A REGEX FOR 5+ LETTERS
$rgx = '/^[A-Z]{5,}$/i';

if (isset($_GET['q']))
{
    if (preg_match($rgx, $_GET['q']))
    {
        echo 'GOOD INPUT OF 5+ LETTERS IN ';
    }
    else
    {
        echo "VALIDATION OF {$_GET['q']} FAILED FOR REGEX: $rgx";
    }
}

// CREATE THE FORM
$form = <<<ENDFORM
<form>
<input type="text" name="q" pattern="[A-Za-z]{5,}" title="At least 5 alphabetic characters" />
<input type="submit" />
</form>
ENDFORM;
echo $form;
like image 35
Ray Paseur Avatar answered Feb 22 '23 22:02

Ray Paseur