Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Improved form validation rule error messages. #961

Merged
merged 10 commits into from
Dec 14, 2012
52 changes: 26 additions & 26 deletions system/language/english/form_validation_lang.php
Original file line number Diff line number Diff line change
Expand Up @@ -26,32 +26,32 @@
*/
defined('BASEPATH') OR exit('No direct script access allowed');

$lang['required'] = 'The %s field is required.';
$lang['isset'] = 'The %s field must have a value.';
$lang['valid_email'] = 'The %s field must contain a valid email address.';
$lang['valid_emails'] = 'The %s field must contain all valid email addresses.';
$lang['valid_url'] = 'The %s field must contain a valid URL.';
$lang['valid_ip'] = 'The %s field must contain a valid IP.';
$lang['min_length'] = 'The %s field must be at least %s characters in length.';
$lang['max_length'] = 'The %s field cannot exceed %s characters in length.';
$lang['exact_length'] = 'The %s field must be exactly %s characters in length.';
$lang['alpha'] = 'The %s field may only contain alphabetical characters.';
$lang['alpha_numeric'] = 'The %s field may only contain alpha-numeric characters.';
$lang['alpha_dash'] = 'The %s field may only contain alpha-numeric characters, underscores, and dashes.';
$lang['numeric'] = 'The %s field must contain only numbers.';
$lang['is_numeric'] = 'The %s field must contain only numeric characters.';
$lang['integer'] = 'The %s field must contain an integer.';
$lang['regex_match'] = 'The %s field is not in the correct format.';
$lang['matches'] = 'The %s field does not match the %s field.';
$lang['differs'] = 'The %s field must differ from the %s field.';
$lang['is_unique'] = 'The %s field must contain a unique value.';
$lang['is_natural'] = 'The %s field must only contain digits.';
$lang['is_natural_no_zero'] = 'The %s field must only contain digits and must be greater than zero.';
$lang['decimal'] = 'The %s field must contain a decimal number.';
$lang['less_than'] = 'The %s field must contain a number less than %s.';
$lang['less_than_equal_to'] = 'The %s field must contain a number less than or equal to %s.';
$lang['greater_than'] = 'The %s field must contain a number greater than %s.';
$lang['greater_than_equal_to'] = 'The %s field must contain a number greater than or equal to %s.';
$lang['required'] = 'The {field} field is required.';
$lang['isset'] = 'The {field} field must have a value.';
$lang['valid_email'] = 'The {field} field must contain a valid email address.';
$lang['valid_emails'] = 'The {field} field must contain all valid email addresses.';
$lang['valid_url'] = 'The {field} field must contain a valid URL.';
$lang['valid_ip'] = 'The {field} field must contain a valid IP.';
$lang['min_length'] = 'The {field} field must be at least {param} characters in length.';
$lang['max_length'] = 'The {field} field cannot exceed {param} characters in length.';
$lang['exact_length'] = 'The {field} field must be exactly {param} characters in length.';
$lang['alpha'] = 'The {field} field may only contain alphabetical characters.';
$lang['alpha_numeric'] = 'The {field} field may only contain alpha-numeric characters.';
$lang['alpha_dash'] = 'The {field} field may only contain alpha-numeric characters, underscores, and dashes.';
$lang['numeric'] = 'The {field} field must contain only numbers.';
$lang['is_numeric'] = 'The {field} field must contain only numeric characters.';
$lang['integer'] = 'The {field} field must contain an integer.';
$lang['regex_match'] = 'The {field} field is not in the correct format.';
$lang['matches'] = 'The {field} field does not match the {param} field.';
$lang['differs'] = 'The {field} field must differ from the {param} field.';
$lang['is_unique'] = 'The {field} field must contain a unique value.';
$lang['is_natural'] = 'The {field} field must only contain digits.';
$lang['is_natural_no_zero'] = 'The {field} field must only contain digits and must be greater than zero.';
$lang['decimal'] = 'The {field} field must contain a decimal number.';
$lang['less_than'] = 'The {field} field must contain a number less than {param}.';
$lang['less_than_equal_to'] = 'The {field} field must contain a number less than or equal to {param}.';
$lang['greater_than'] = 'The {field} field must contain a number greater than {param}.';
$lang['greater_than_equal_to'] = 'The {field} field must contain a number greater than or equal to {param}.';

/* End of file form_validation_lang.php */
/* Location: ./system/language/english/form_validation_lang.php */
25 changes: 23 additions & 2 deletions system/libraries/Form_validation.php
Original file line number Diff line number Diff line change
Expand Up @@ -615,7 +615,7 @@ protected function _execute($row, $rules, $postdata = NULL, $cycles = 0)
}

// Build the error message
$message = sprintf($line, $this->_translate_fieldname($row['label']));
$message = $this->_build_error_msg($line, $this->_translate_fieldname($row['label']));

// Save the error message
$this->_field_data[$row['field']]['error'] = $message;
Expand Down Expand Up @@ -767,7 +767,7 @@ protected function _execute($row, $rules, $postdata = NULL, $cycles = 0)
}

// Build the error message
$message = sprintf($line, $this->_translate_fieldname($row['label']), $param);
$message = $this->_build_error_msg($line, $this->_translate_fieldname($row['label']), $param);

// Save the error message
$this->_field_data[$row['field']]['error'] = $message;
Expand Down Expand Up @@ -806,6 +806,27 @@ protected function _translate_fieldname($fieldname)
return $fieldname;
}

// --------------------------------------------------------------------

/**
* Build an error message using the field and param.
*
* @param string The error message line
* @param string A field's human name
* @param mixed A rule's optional parameter
* @return string
*/
protected function _build_error_msg($line, $field = '', $param = '')
{
// Check for %s in the string for legacy support.
if (strpos($line, '%s') !== FALSE)
{
return sprintf($line, $field, $param);
}

return str_replace(array('{field}', '{param}'), array($field, $param), $line);
}

// --------------------------------------------------------------------

/**
Expand Down
185 changes: 88 additions & 97 deletions user_guide_src/source/libraries/form_validation.rst
Original file line number Diff line number Diff line change
Expand Up @@ -139,7 +139,6 @@ this code and save it to your application/controllers/ folder::
}
}
}
?>

Try it!
=======
Expand Down Expand Up @@ -240,7 +239,6 @@ Your controller should now look like this::
}
}
}
?>

Now submit the form with the fields blank and you should see the error
messages. If you submit the form with all the fields populated you'll
Expand Down Expand Up @@ -436,7 +434,7 @@ Here's how your controller should now look::
{
if ($str == 'test')
{
$this->form_validation->set_message('username_check', 'The %s field can not be the word "test"');
$this->form_validation->set_message('username_check', 'The {field} field can not be the word "test"');
return FALSE;
}
else
Expand All @@ -446,7 +444,6 @@ Here's how your controller should now look::
}

}
?>

Reload your form and submit it with the word "test" as the username. You
can see that the form field data was passed to your callback function
Expand All @@ -469,7 +466,7 @@ Setting Error Messages
======================

All of the native error messages are located in the following language
file: language/english/form_validation_lang.php
file: system/language/english/form_validation_lang.php

To set your own custom message you can either edit that file, or use the
following function::
Expand All @@ -479,29 +476,23 @@ following function::
Where rule corresponds to the name of a particular rule, and Error
Message is the text you would like displayed.

If you include %s in your error string, it will be replaced with the
"human" name you used for your field when you set your rules.
If you'd like to include a field's "human" name, or the optional
parameter some rules allow for (such as max_length), you can add the
**{field}** and **{param}** tags to your message, respectively.

In the "callback" example above, the error message was set by passing
the name of the function::
$this->form_validation->set_message('min_length', '{field} must have at least {param} characters.');

$this->form_validation->set_message('username_check')

If you are using an error message that can accept two $s in your error string,
such as:
::

$this->form_validation->set_message('min_length', 'The $s field must contain at least $s characters.');

Then you can also use %1$s and %2$s:
::
On a field with the human name Username and a rule of min_length[5], an
error would display: "Username must have at least 5 characters."

$this->form_validation->set_message('min_length', 'This field must contain at least %2$s characters.');
.. note:: The old method of using **%s** in your error messages will
still work, however it will override the tags above. You should use
one or the other.

You can also override any error message found in the language file. For
example, to change the message for the "required" rule you will do this::
In the callback rule example above, the error message was set by passing
the name of the function (without the "callback_" prefix)::

$this->form_validation->set_message('required', 'Your custom message here');
$this->form_validation->set_message('username_check')

.. _translating-field-names:

Expand Down Expand Up @@ -613,7 +604,7 @@ In this case, you can specify the array to be validated::

$this->form_validation->set_data($data);

Creating validation rules, running the validation and retrieving error messages works the
Creating validation rules, running the validation, and retrieving error messages works the
same whether you are validating ``$_POST`` data or an array.

**Important Note:** If you want to validate more than one array during a single execution, then you should
Expand Down Expand Up @@ -678,56 +669,56 @@ rules. We've arbitrarily called these two rules "signup" and "email".
You can name your rules anything you want::

$config = array(
'signup' => array(
array(
'field' => 'username',
'label' => 'Username',
'rules' => 'required'
),
array(
'field' => 'password',
'label' => 'Password',
'rules' => 'required'
),
array(
'field' => 'passconf',
'label' => 'PasswordConfirmation',
'rules' => 'required'
),
array(
'field' => 'email',
'label' => 'Email',
'rules' => 'required'
)
),
'email' => array(
array(
'field' => 'emailaddress',
'label' => 'EmailAddress',
'rules' => 'required|valid_email'
),
array(
'field' => 'name',
'label' => 'Name',
'rules' => 'required|alpha'
),
array(
'field' => 'title',
'label' => 'Title',
'rules' => 'required'
),
array(
'field' => 'message',
'label' => 'MessageBody',
'rules' => 'required'
)
)
);
'signup' => array(
array(
'field' => 'username',
'label' => 'Username',
'rules' => 'required'
),
array(
'field' => 'password',
'label' => 'Password',
'rules' => 'required'
),
array(
'field' => 'passconf',
'label' => 'Password Confirmation',
'rules' => 'required'
),
array(
'field' => 'email',
'label' => 'Email',
'rules' => 'required'
)
),
'email' => array(
array(
'field' => 'emailaddress',
'label' => 'EmailAddress',
'rules' => 'required|valid_email'
),
array(
'field' => 'name',
'label' => 'Name',
'rules' => 'required|alpha'
),
array(
'field' => 'title',
'label' => 'Title',
'rules' => 'required'
),
array(
'field' => 'message',
'label' => 'MessageBody',
'rules' => 'required'
)
)
);

Calling a Specific Rule Group
=============================

In order to call a specific group you will pass its name to the ``run()``
In order to call a specific group, you will pass its name to the ``run()``
method. For example, to call the signup rule you will do this::

if ($this->form_validation->run('signup') == FALSE)
Expand Down Expand Up @@ -770,29 +761,29 @@ In your validation config file, you will name your rule group
member/signup::

$config = array(
'member/signup' => array(
array(
'field' => 'username',
'label' => 'Username',
'rules' => 'required'
),
array(
'field' => 'password',
'label' => 'Password',
'rules' => 'required'
),
array(
'field' => 'passconf',
'label' => 'PasswordConfirmation',
'rules' => 'required'
),
array(
'field' => 'email',
'label' => 'Email',
'rules' => 'required'
)
)
);
'member/signup' => array(
array(
'field' => 'username',
'label' => 'Username',
'rules' => 'required'
),
array(
'field' => 'password',
'label' => 'Password',
'rules' => 'required'
),
array(
'field' => 'passconf',
'label' => 'PasswordConfirmation',
'rules' => 'required'
),
array(
'field' => 'email',
'label' => 'Email',
'rules' => 'required'
)
)
);

When a rule group is named identically to a controller class/function it
will be used automatically when the run() function is invoked from that
Expand Down Expand Up @@ -928,8 +919,8 @@ Name Parameter Description
**encode_php_tags** No Converts PHP tags to entities.
==================== ========= ===================================================================================================

.. note:: You can also use any native PHP functions that permit one
parameter, like trim, htmlspecialchars, urldecode, etc.
.. note:: You can also use any native PHP functions that permits one
parameter, like ``trim()``, ``htmlspecialchars()``, ``urldecode()``, etc.

.. _function-reference:

Expand Down Expand Up @@ -1087,5 +1078,5 @@ This function is identical to the **set_checkbox()** function above.

::

<input type="radio" name="myradio" value="1" <?php echo set_radio('myradio', '1', TRUE); ?> />
<input type="radio" name="myradio" value="2" <?php echo set_radio('myradio', '2'); ?> />
<input type="radio" name="myradio" value="1" <?php echo set_radio('myradio', '1', TRUE); ?> />
<input type="radio" name="myradio" value="2" <?php echo set_radio('myradio', '2'); ?> />