The code in controller is as follows:
for(o in options){
if(o){
if(!o.isInteger()){
don.errors.reject("The value was not integer")
render(view: "editdonation", model: [id:id, donation:don])
return
}
don.addToDenominations(o.toInteger())
}
}
I intentionally pass in invalid input so that the don.errors.reject() code is executed.
The editdonation.gsp has the following code to print the error in the donation object.
<ul class="inline-errors" role="alert">
<g:hasErrors bean="${donation}">
<div class="errors">
ok it has errors
</div>
</g:hasErrors>
</ul>
Why is the view not displaying the error? I appreciate any help!
The Errors.reject() method expects an error code rather than an error description.
Creating the error code
To create your own error code:
Edit the file grails-app/i18n/message.properties
Add a new line with your error code. Ex: option.donation.notinteger=The option value {0} was not an Integer
Save the file grails-app/i18n/message.properties
Using the error code
To use the error code, call Errors.reject() like this:
don.errors.reject('option.donation.notinteger', [o] as Object[], 'The value was not integer')
The code above passes the option to reject so that it can insert the value into the error message. And as required, it provides a fallback error message.
Related
I have a List Which i am checking within my Custom Validation attribute. List Renders like this on my VIEW
<input type="check" value="Bath">
<input type="check" value="Food">
and my Custom Validator is...
public class MyAttribute: ValidationAttribute
{
// some logic and then
// Get Data from some webservice
// Make sure CERTAIN checkboxes are selected
// If Bath was NOT checked then
return new ValidationResult("Bath is Required")
// If Food was NOT checked then
return new ValidationResult("Food is Required")
}
Now this works fine & I can show the error message "Some Error" on my view, However my issue is I want to show the RED ERROR BOX around the checkbox which was REQUIRED to check. Currently i am just showing a Error message string on my VIEW. It would be nice for user to see what was REQUIRED.
You can pass a style attribute as the 3rd Argument to the ValidationMessageFor method in razor view as such:
#Html.ValidationMessageFor(m=>m.StudentName, "", new { #style="color:red" })
You can also run your application trigger the validation message, in chrome, right click the validation message and inspect element, go to the debugger window and trace the class associated with the validation error message.
Go to site.css and overwrite the default validation-error message class as shown below:
span.field-validation-error {
background-color: #ffeeee;
outline: 1px solid #ff0000;
}
Hope this will help.
I confirm that the errors on on the object before I send them to the view
trip.riders.each{rider->
rider.errors.each{it->
//visually confirming to myself the errors are there
println it;
}
}
render(view:'edit',model:[trip:trip);
return;
The error I am confirming prints to console "Field error in object on field 'mileage'...."
Yet when rendered
<g:each in="${trip?.riders}" var="rdr" status='i'>
<div class='form-category'>
<div class='error'>
<g:hasErrors bean="${rdr}" field="mileage">
<g:renderErrors bean="${rdr}" field="mileage" as="list" />
</g:hasErrors>
No errors show up. What could be happening here?
UPDATE
I believe the problem is along these lines...
http://forum.spring.io/forum/other-spring-related/grails/97568-haserrors-true-disappears
Seems hibernate persists things in some instances in a way that causes validation errors to be cleared.
Try
<g:hasErrors>
<g:eachError> ${it} </g:eachError>
</g:hasErrors>
If you have added custom errors using "rejectValue()" method, validate() or save() method will remove custom errors added to the domain instance
I have the next constraint in my domain object usuario/Usuario.groovy:
phone blank: false, matches: "[0-9 -+()]{3,15}"
And I have in i18n/messages_es.properties:
usuario.telefono.matches=Se admiten números, espacios y los caracteres: -+(). Se admiten entre 3 y 15 caracteres en total.
This is the error message if the phone doesn't match the pattern:
The translation of the message would be something like: "Please, adjust the requested format"
I have not any similar error message in any of the i18n/messages... files. It looks a client side error message as it appears instantly.
In create gsp there is the next code (I think the error message could come from here):
<g:hasErrors bean="${usuarioInstance}">
<bootstrap:alert class="alert-error">
<ul>
<g:eachError bean="${usuarioInstance}" var="error">
<li <g:if test="${error in org.springframework.validation.FieldError}">data-field-id="${error.field}"</g:if>><g:message error="${error}"/></li>
</g:eachError>
</ul>
</bootstrap:alert>
</g:hasErrors>
How could I change this error message by a custom one?
The first thing you have to understand: this message is html form validation error and doesn't connected to your application messages. So the fix will be in html. Try to add oninvalid attribut to input tag:
<input type="text" name="phone" pattern="[0-9 -+()]{3,15}" required="" value="" id="phone" oninvalid="setCustomValidity('Please, type valid phone number')">
You can move 'Please, type valid phone number' to i18n file
Edit: if you use fields plugin add oninvalid attr with input- prefix.
<f:field bean="${usuarioInstance}" property="phone" input-oninvalid="setCustomValidity('Please, type valid phone number')"/>
I think you are missing 'invalid' as part of the message key.
Use the following error code for matches:
className.propertyName.matches.invalid = 'errorMessage'..
Still if it doesn't work ..try the following approach.
Add def messageSource in controller /service.
user.errors?.allErrors?.each{
println messageSource.getMessage(it, null)
};
Go through the following link which explains this better
http://johnrellis.blogspot.com/2010/02/retrieve-grails-domain-errors-from.html
My razor view page looks like:
#foreach (var comment in Model.Comments)
{
#Html.RenderPartial("Comment", comment);
}
And my partial view is in /Shared/Comment.cshtml
#model Comment
<div>
<span class="user">#Model.Name</span>
...
</p>
I'm getting this error:
Compilation Error
Description: An error occurred during the compilation of a resource required to service this request. Please review the following specific error details and modify your source code appropriately.
Compiler Error Message: CS1502: The best overloaded method match for 'System.Web.WebPages.WebPageExecutingBase.Write(System.Web.WebPages.HelperResult)' has some invalid arguments
(it then highlights the call to #Html.RenderPartial("Comment", comment);
You don't need the '#' in front of Html since it is stated before any html:
#foreach (var comment in Model.Comments)
{
Html.RenderPartial("Comment", comment);
}
Additionally, Html.RenderPartial doesn't return anything. So, it must be executed in a code block (the case above counts).
The #[some method] syntax is only valid for methods that return something that Razor can convert to a string.
Currently I use this to check if a tab(element) already exists:
if(!$('#'+element).length){
//... code to add new tab if not exists.
} else {
Alert("Tab or portlet already exists...");
}
This is very dirty and I get a "uncaught exception: Syntax error, unrecognized expression: #" from FireBug. If element already exists, the "Alert" doesn't show, I think it hangs at the first exception.
Is there a better way to check if an element exists? (Or a tab)
I am using this for my personal project # http://www.soliman.nl/test/jqueryui/ui_2.php
The problem seems to be in your source - you are passing "#foo" as the parameter element, then prepending another "#". The result is $("##foo"), which just isn't going to work.
please check value of element
coz if this is null or empty your statement become
if(!$('#').length){
or
if(!$('#null').length){
which may through some error
here is working version
<html>
<body>
<p id="test"></p>
</body>
</html>
var element = "test"; //if you try to comment this line or change value , it will give error
if(!$('#'+element).length){
alert("do something");
} else {
alert("Tab or portlet already exists...");
}
Demo
http://jsfiddle.net/J3MdK/