Add custom error messages to CI validation_errors() - php

There's a way to add custom error messages to CodeIgniter validation_errors();?
Example, if I wanted a field with a 123456 value, and the user inputs 12345 I'd want to set a message to say:
The number 6 is required!
And any other custom rules I may want to add. Like a specific pattern or any other things.
Sorry for my english.

Yes, that is possible.
Set rules with callback like,
$this->form_validation->set_rules('field_name', 'Number', 'callback_custom_validation');
and define callback in the same controller like,
public function custom_validation($str)
{
if ($str != '123456')
{
$this->form_validation->set_message('field_name', 'The %s field requires 123456');
return false;
}
else
{
return true;
}
}
Display your errors in view with <?php echo form_error('field_name')?>
More info on callbacks here.

Related

Drupal multiple custom field required, pass validation if field is empty

I've build a custom field with several values. I've to make this field required. But I want to pass the validation if at least one field is filled and the last one is empty.
But my problem is Drupal warn me that the last (empty) field is required. I've thought that the hook_field_is_empty() solved the problem, but, even if return true, the form cannot be validated.
Many thanks for your help.
Implementation :
function MYMODULE_field_widget_form(...) {
$element['address']+=[
...
'#required' => $instance['required'],
];
...
}
function MYMODULE_field_is_empty($item, $field) {
if (empty($item['address']) && empty($item['other'])) {
return true ;
}
return false ;
}
To solve this problem, I've made my field not required (in the definition of the node's fields). Then, I added a callback in the #validate using the hook_form_alter(). In that callback, I test if at least one field is defined and call a form_set_error() if none is defined.
This makes sense because it's not the field itself that could know all the data of the node. But, something is a bit wrong because it's not possible to mark this field as required (e.g. asterisks).
<?php
function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
if ($formid == ...) { // a specific case
array_unshift($form['#validate'], '_MYMODULE_validate_form') ;
}
}
function _MYMODULE_validate_form(&$form, &$form_state) {
if (empty($form_state['values']['field_geo'][LANGUAGE_NONE][0]['address'])) {
form_set_error('field_geo', t('You have to define at least one address.')) ;
}
}
?>

Laravel - both input values can't be no how to validate?

I'm using Laravel for a project and want to know how to validate a particular scenario I'm facing. I would like to do this with the native features of Laravel if this is possible?
I have a form which has two questions (as dropdowns), for which both the answer can either be yes or no, however it should throw a validation error if both of the dropdowns equal to no, but they can both be yes.
I've check the laravel documentation, but was unsure what rule to apply here, if there is one at all that can be used? Would I need to write my own rule in this case?
very simple:
let's say both the fields names are foo and bar respectively.
then:
// Validate for those fields like $rules = ['foo'=>'required', 'bar'=>'required'] etc
// if validation passes, add this (i.e. inside if($validator->passes()))
if($_POST['foo'] == 'no' && $_POST['bar'] == 'no')
{
$messages = new Illuminate\Support\MessageBag;
$messages->add('customError', 'both fields can not be no');
return Redirect::route('route.name')->withErrors($validator);
}
the error messge will appear while retrieving.
if you get confuse, just dump the $error var and check how to retrieve it. even if validation passes but it gets failed in the above code, it won't be any difference than what would have happened if indeed validation failed.
Obviously don't know what your form fields are called, but this should work.
This is using the sometimes() method to add a conditional query, where the field value should not be no if the corresponding field equals no.
$data = array(
'field1' => 'no',
'field2' => 'no'
);
$validator = Validator::make($data, array());
$validator->sometimes('field1', 'not_in:no', function($input) {
return $input->field2 == 'no';
});
$validator->sometimes('field2', 'not_in:no', function($input) {
return $input->field1 == 'no';
});
if ($validator->fails()) {
// will fail in this instance
// changing one of the values in the $data array to yes (or anything else, obvs) will result in a pass
}
Just to note, this will only work in Laravel 4.2+

JForm - Multiple Validation Rules?

I have a form (defined in XML) which is used with Joomla's JForm to handle. What I'd like to know is if it's possible to validate against multiple rules at once.
Typically, I've come to understand that Joomla's JForm accepts only one rule for validation, defined in the XML of the form:
Joomla's JForm internals also seem to suggest I can't, the following area being the only one I can find handing validation:
// Get the field validation rule.
if ($type = (string) $element['validate'])
{
// Load the JFormRule object for the field.
$rule = $this->loadRuleType($type);
// If the object could not be loaded return an error message.
if ($rule === false)
{
throw new UnexpectedValueException(sprintf('%s::validateField() rule `%s` missing.', get_class($this), $type));
}
// Run the field validation rule test.
$valid = $rule->test($element, $value, $group, $input, $this);
// Check for an error in the validation test.
if ($valid instanceof Exception)
{
return $valid;
}
}
This isn't wrapped in a loop, so I'm quite concerned that I can't apply multiple rules at once to a particular field.
Are you looking for server or client side validation? Sean's answer seems to cover server side so I figured I'd add some insight into client side techniques.
You enable client side validation two ways. The first and simplest would be by adding the following to your form field definition, which would ensure any required fields are filled out to proceed.
required="true"
Second would be to add a class to the form field definition to let Joomla core know you want to validate the field and how. Joomla offers 4 validations built into the core: validate-username, validate-password, validate-numeric and validate-email.
These in and of themselves don't help you much, but the ability to create and reference custom client-side validations does. For my example we're going to ensure a check box is marked before allowing the form to submit. So in the form field definition I'll add:
class="validate-checked"
On the page where you render the form, be sure to load the JS library for validation using:
JHtml::_('behavior.formvalidation');
In addition, add the class form-validate to your form HTML element.
Add this javascript to handle the actual validation, here I have a checkbox input type with an ID of tos I'm verifying. In the setHandler method, the first parameter is the custom name I entered in the form field definition class statement, validate-checked:
<script>
window.addEvent('domready', function(){
document.formvalidator.setHandler('checked', function(value) {
var tos = document.getElementById('tos');
if (tos.checked) {
return true;
} else {
return false;
}
});
});
</script>
Now, capture the submit event and verify all core and custom validations passed before submitting the form.
Joomla.submitbutton = function(task) {
if (task == 'user.cancel' || document.formvalidator.isValid(document.id(".myFormId"))) {
Joomla.submitform(task, document.getElementById('myformId'));
}
You can create as many custom client-side validation scripts as you want. Inside the setHandler method you can interact with the DOM and use the passed in value parameter to determine if the field should pass, only needing to worry about returning true or false to indicate results and Joomla will handle the rest. So you can either create one complicated validation or many smaller concise validations to suit your needs.
Hope that helps...
This is a common request. There are a few possibilities. You could write your own JFormRule with more complex validation. The other is that you could programatically add an attribute to the field that runs the additional validation sort of like what Sean is advocating.
This answer assumes that it is not possible to natively add multiple rules on one field.
Assuming that it is not possible to apply multiple rules to one field natively, then it may be possible to extend JForm::validateField() to enable such a feature by simply calling the validate method for each validation rule found.
// Extending class JForm
protected function validateField(SimpleXMLElement $element, $group = null, $value = null, JRegistry $input = null) {
if($type = (string) $element['validate'])
{
$multiple_types = explode('|', $type);
if(is_array($multiple_types) && $multiple_types[0] !== $type)
{
foreach($multiple_types as $single_type)
{
$result = parent::validateField($element, $group, $value, $input);
// Validation failed, return the result and stop validating.
if($result !== true)
{
return $result;
}
}
return true;
}
else
{
return parent::validateField($element, $group, $value, $input);
}
}
}
With that example, validation rules could be structured like:
validate="rule1|rule2"

CodeIgniter num_rows() not working?

Ok I don't know what's not working. I know my form validation is definitely working because all my other functions work properly, but I am setting messages whether it's true OR false and none of them show up so I feel like it's skipping right over the validation rule.. which is weird...
$this->form_validation->set_rules('region', 'required|valid_region');
The rule in MY_Form_validation.php in my libraries folder. The library IS loaded first. As I said all my other validations work properly such as my reCaptcha and everything.
function valid_region($str) {
$this->load->database();
if($this->db->query('SELECT id
FROM region
WHERE name = ?
LIMIT 1', array($str))->num_rows() == 0) {
//not a valid region name
$this->set_message('valid_region', 'The %s field does not have a valid value!');
return false;
}
$this->set_message('valid_region', 'Why is it validating?');
}
None of the messages will set so I have a feeling nothing is validating!
set_rules() function takes 3 parameters
The field name - the exact name you've given the form field.
A "human" name for this field, which will be inserted into the error message.
For example, if your field is named "user" you might give it a human
name of "Username". Note: If you would like the field name to be
stored in a language file, please see Translating Field Names.
The validation rules for this form field.
You put the validation rules as second parameter. That is why the validation is not running. Try this instead:
$this->form_validation->set_rules('region', 'Region', 'required|valid_region');
instead of
$this->form_validation->set_rules('region', 'required|valid_region');
try
$this->form_validation->set_rules('region', 'required|callback_valid_region');
when using custom validation rules you should use
callback to prepend the function name.
UPDATE
and use
$this->form_validation->set_message
instead of
$this->set_message
and in function valid_region
use return true when validation is successfull
$this->form_validation->set_rules('region', 'Region', 'required|valid_region');
function valid_region() {
$str = $this->input->post('name_of_input');
$this->load->database();
if($this->db->query('SELECT id
FROM region
WHERE name = ?
LIMIT 1', array($str))->num_rows() == 0) { // why compare "=" between `name` field and array() ?
//not a valid region name
$this->form_validation->set_message('valid_region', 'The %s field does not have a valid value!');
return false;
}
$this->form_validation->set_message('valid_region', 'Why is it validating?');
return true;
}

How do I write a custom validator for a zend form element with customized error messages?

I have a question field with a list of allowed characters : A-Z,0-9,colon (:), question mark (?), comma(,), hyphen(-), apostrophe (').
I have the regex which works fine, in the fashion :
$question->addValidator('regex', true, array(<regular expresstion>))
The default error message is something like ''' does not match against pattern ''
I want to write a custom error message that says ' is not allowed in this field'
Is there a simple way to do it using the existing zend components that I'm missing?
Is writing a custom validator the only way to achieve what I'm trying to achieve?
If yes, how do I write a custom validator (I looked at the documentation and didn't quite understand how I can customize the error messages)
If there is any other way, I'd most appreciate that input too.
Thanks for taking the time to answer this!
Yes, the custom validator fits your needs. On how to write it, please refer to this manual.
With regards to a code snippet, here's a simple validator(partial) for validating employer ID
protected $_messageTemplates = array(
self::UNIQUE => 'The id provided is already in use',
);
public function isValid($value, $context = null)
{
$this->_setValue($value);
$personnel = new Personnel();
$isValid = true;
if( $personnel->isExistingIdEmployee($value) && ($value != $this->_id) ) {
$this->_error(self::UNIQUE);
$isValid = false;
}
return $isValid;
}

Categories