How to 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 an easy way to make me require 5 characters and show an error message if it's not just letters.

+4
source share
5 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 you to get exactly 5 characters, which can only be uppercase or lowercase letters.

+3
source

Perhaps you can do this in jQuery on the client side. You will also need to do this on the server side, as JavaScript can (and will) bypass the attack vector. A regular expression like this will perform server side validation in PHP.

$ rgx = '/ [AZ] {5,} / i';

The combination of 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 = '/^[AZ]{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; 
+2
source
 <input type="text" pattern=".{5,}" required /> 

try it

+1
source

Validate the form before viewing like this, and use the strlen parameter to check the input length:

 if(isset($_POST['mySubmit'])) { if(strlen($_POST['try']) < 5) { $error = "Too short"; } else { $valid = true; //Do whathever you need when form is valid } } else { if(isset($error)) { echo "<p>$error</p>"; } //echo your form here echo "<form method='post' action='thisPhpScript.php'> <input type='text' name='try' size='10' id='try' maxlength='5' > </form>"; } 

Not tested, so they may have syntax errors.

+1
source

Assuming the page is submitting itself.

Fast and dirty.

 <?php $errors = array(); if (isset($_POST['try']) & strlen($_POST['try']) != 5 & ctype_alpha( $_POST['try'] != true) { $error['try'] = "This field must contains 5 characters and contain only az and AZ"; // stop whatever you normally do if submitted. } ?> 

Further on the page where you show this field.

 <?php if (isset($errors['try'])) { echo $errors['try']; } ?> <input type="text" name="try" size="10" id="try" maxlength="5" > 
+1
source

All Articles