Codeigniter Form Validation - Is there a way to define multiple different %s when setting error messages? - codeigniter

Based on the documentation, %s will be replaced by field name when setting error messages.
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.
Is there a way to have multiple %s in the string and define them differently?

This is the line in the form validation library that creates the error message:
// Build the error message
$message = sprintf($line, $this->_translate_fieldname($row['label']), $param);
$line: The error message template, for example "The % field is invalid"
$this->_translate_fieldname($row['label']): The field's label
$param: The parameter passed the the validation function, if any, max_length[5] would pass "5"
So that's the extent of what the form validation class does for you. If you need more flexibility you'll have to prepare the error message yourself <-- might be useful beforehand with the extra variables already populated.
It might be interesting to extend the form validation class via core/MY_form_validation.php and work this functionality in. Unfortunately this line is contained in the main function _execute which is very big and messy, and from looking at it now, you'd need to overload some other functions as well. I started to write an example but it actually looks like a chore. You might be better off using:
$this->form_validation->set_message('rule_name', 'Your custom message here');
More on setting error messages: http://ellislab.com/codeigniter/user_guide/libraries/form_validation.html#settingerrors

Related

How to map an input validation error to a specific error code in Spring

I am having a case in which I would like to do some input validation on the #RequestParams of an endpoint.
I know about Validators and Custom Validators, and my current strategy implies creating a wrapper object around the RequestParams, a custom validator and apply class level the annotation that triggers the custom validation.
My problem is that the custom validation is implementing ConstraintValidator, which means that the validator will either return true or false, and an error will be created by Spring with some text (I also know that I can change this text). My desire, however, is to create a custom payload back to the client. An example could be
class MyError {
int code;
String message;
}
The way to return this object is through a #ControllerAdvice Error handler, which understands that a ConstraintValidationException should return my custom payload format. However, I need to return different codes and messages for different reasons on the input validation failed. For example:
A Field is empty -> code XXX
A Field is formatted incorrectly -> code YYY
As far as I know, there is little customization possible on the exception that is reachable from my #ControllerAdvice, I can get a list of errors that happened but I cannot easily determine what happened. (Technically I can, but it would have to be based on the message string, which is pretty weak).
Is there a way to provide extra data to the Exception so I can distinguish from the #ControllerAdvice what happened and create my custom error response accordingly?
Am I approaching it the wrong way?
You can intercept the BindException (https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/validation/BindException.html) with the #ExceptionHandler. This contains detailed information about all validation errors. For example, with e.getFieldErrors() you can access all errors associated with fields.
For example, for a field
#MyConstraint
#Length(min = 3)
private String field;
that failed validation you get the following information in the exception:
Field error in object data on field field: rejected value [XY]; codes [Length.data.field,Length.field,Length.java.lang.String,Length].
Field error in object data on field field: rejected value [XY]; codes [MyConstraint.data.field,MyConstraint.field,MyConstraint.java.lang.String,MyConstraint].
From this you can see that it failed the #Length constraint and the custom #MyConstraint constraint.

codeigniter form validation can't set_rules if using a config file

My config file with my validation rules works fine when calling the form_validation->run('form'). The thing is that I want to set custom error message for one of the fields. So in the controller I just add: ..set_message('field','message'). But it's not registering, I get the default error message: .... is required.
For changing the message for the existing validation rules, just do the following.
Copy the form_validation_lang.php file from system/language/english to application/language/english
Modify the message for your validation rule name.
For example for changing message for required field change the below line.
$lang['required'] = "The %s field is required.";

Difference between an error code and a message code as far as Spring validation is concerned?

I am in reference to the following method from BindingResult:
BindingResult.html#resolveMessageCodes(java.lang.String, java.lang.String)
I am trying to figure out the difference between an error code and a message code. Can someone please provide an example, especially one that would illustrate why there could be several message codes for a given error code?
Because web applications are internationalized, when you reject an object and want to have a message displayed for it, you don't use a hardcoded text because that will show the same no matter the language.
Instead, you specify an error code that later server as a key to retrieving the proper message from the bundles (and now the error code is a message code from the point of view of the method that must find the proper message text).
Your error code resolves to more message codes because Spring (based on the implementation) adds some additional ones for you. Here is a snippet from the Spring documentation:
[...] What error codes it registers is determined by the MessageCodesResolver that is used. By default, the DefaultMessageCodesResolver is used, which for example not only registers a message with the code you gave, but also messages that include the field name you passed to the reject method. So in case you reject a field using rejectValue("age", "too.darn.old"), apart from the too.darn.old code, Spring will also register too.darn.old.age and too.darn.old.age.int (so the first will include the field name and the second will include the type of the field); this is done as a convenience to aid developers in targeting error messages and suchlike. [...]
The last statement is the reason there are more message codes, to have control on the message that is displayed to the user, from a generic one (e.g. "Value required") to a more specific one given the context (e.g. "A value is required for field XXX").
The javadoc for DefaultMessageCodesResolver explains it further and gives an example:
For example, in case of code "typeMismatch", object name "user", field "age":
try "typeMismatch.user.age"
try "typeMismatch.age"
try "typeMismatch.int"
try "typeMismatch"
This resolution algorithm thus can be leveraged for example to show specific messages for binding errors like "required" and "typeMismatch":
at the object + field level ("age" field, but only on "user");
at the field level (all "age" fields, no matter which object name);
or at the general level (all fields, on any object).

Is there a way to make angular run all the validations of an input instead of stoping when the first validation fails?

I'm having problems trying to make angular run all the validations of an input at once.
Here is a jsfiddle example of my problem http://jsfiddle.net/carpasse/GDDE2/
if you type 1 character on the email input you get this "The minimum lenght is 3." error message
and is not until you type 2 more characters than you get the other error message "This is not a valid email."
Does anybody know how to make angular show both error messages at the same time??
Thanks a lot in advance
You problem is not that all the validators are not being run - they are!
Remember that the way these validations work is by passing the view values through a pipeline of transformation functions, which can also specify the validity of the value.
The problem is that the min length validator passes undefined down the pipeline if it is not valid and that the email validator says that undefined is a valid email address!
Try creating your own validation directive that says that undefined is not a valid email address and you will find both errors are showing: http://jsfiddle.net/eKfj3/

If codeigniter model returns 0 rows, display custom error message. How to extend to a general case?

I have a variety of functions within my models which serve a different purpose.
One for example looks up the data for a given $_GET variable in the URL string.
I am trying to work out a way of displaying an error message if there is no matching row in the database due to url string manipulation for example.
My first idea was simply to return an error message (if there is an error) with each call to the function, then simply have an if statement whereby if there is an error, an error view is shown, and if not the normal view is shown..
Problem with this is that this function is called numerous times in my controller, and other similar functions are called throughout my code which need similar error handling..
I dont want millions of similar if/else statements all over my code to handle errors..
Anyone got any better ideas?
Cheers
Use the flashdata item of the session class. You can concatenate error messages and put them in the flashdata item to display.
my_function(){
// code that determines if there is an error returns => $error
if ($error)
{
// concat previous and current errors
$new_error = $this->session->flashdata('errors') . $error;
// replace 'errors' with newly concatenated errors
$this->session->set_flashdata('errors', $new_error);
}
}
This will keep track of all errors generated through each request and allow you to display a "list" of errors for that particular request.
echo $this->session->flashdata('errors');

Resources