On this page
Min/Max Length
Last updated on
30 April 2025
Below is a PHP snippet to set the minimum length for a field. If the submitted data for that field is too short a helpful error message is provided.
// The field with the key "fullname" must have at least 5 characters.
$minimum_length = 5;
if (strlen($form_values['submitted_tree']['fullname']) < $minimum_length) {
form_set_error('submitted][fullname', 'The name is too short; minimum length is 5 characters.');
}
Alternatively, ensure that a field does not exceed the specified length.
// The field with the key "project_description" must not exceed 500 characters.
$max_len = 500;
$cur_len = strlen($form_values['submitted_tree']['project_description']);
if ($cur_len > $max_len) {
$num_cha = $cur_len - $max_len;
form_set_error("submitted][project_description", "The project description must not exceed 500 characters. Please remove at least $num_cha characters and resubmit. Thank you.");
}
Adding Validation to Your Webform
There are two methods for adding validation to your Webform:
- Insert your php code in the Additional Validation field in the Webform Advanced Settings section (it should be collapsed by default) -- don't forget to surround your code with php tags
- Put your code in a separate php file and include it in the same textarea as step 1. For example, create a directory called sites/all/forms/yourwebform with a file called validation.php in that directory and include it as follows
include $base_path . 'sites/all/forms/yourwebform/validation.php';where yourwebform is the name of your form. This allows you to use an external code editor which is better for text formatting and handling large sets of validation rules.
Useful Links
US telephone number validation
This code doesn't accept periods as seperators xxx.nnn.nnnn but that is fine for most cases.
$useareacode=true;
$phonenumber = $form_values['submitted_tree']['phone'];
if ( !( preg_match("/^[ ]*[(]{0,1}[ ]*[0-9]{3,3}[ ]*[)]{0,1}[-]{0,1}[ ]*[0-9]{3,3}[ ]*[-]{0,1}[ ]*[0-9]{4,4}[ ]*$/",$phonenumber) || (preg_match("/^[ ]*[0-9]{3,3}[ ]*[-]{0,1}[ ]*[0-9]{4,4}[ ]*$/",$phonenumber) && !$useareacode))) form_set_error('submitted][phone', t('Phone number must be in format (xxx) nnn-nnnn.'));
Found the preg_match at codewalkers and tweaked to only return on error.
Help improve this page
Page status: Not set
You can:
You can:
- Log in, click Edit, and edit this page
- Log in, click Discuss, update the Page status value, and suggest an improvement
- Log in and create a Documentation issue with your suggestion