I have the following snippet of code in the Validator which basically is used to show an error message. In the error message I would like to show a link by sending it as a parameter in the error message.
if (user != null && formData.getUserId()== null) {
errors.rejectValue("email", "email.already.exists",new Object[]{"Link "},null);
return;
}
I am unable to get the desired error message on the JSP page . The error is rendered like a string
and is not converted to HTML code. Please help.
Thank you
Manu
<form:errors> has an escapeHtml attribute:
<form:errors escapeHtml = "false" ... />
Note, however, that this may cause undesired behaviour if other error messages displayed by this tag should be escaped.
The attribute is now htmlEscape. See this for reference.
So, if you use <form:errors htmlEscape="false" ... /> then you can have html in the error.
The error variable should only be a string. In your JSP, enclose that string with whatever HTML markup you would like.
Related
I have my messages.properties like this:
tablas.menu.paises=Pa\u00EDses
tablas.menu.regiones=Regiones
tablas.menu.anhos=A\u00F1os
tablas.menu.universidades=Universidades
tablas.menu.usuarios=Usuarios
In the .html I have a menu showing each item with th:each:
<li class="nav-item" th:each="menu : ${menus}">
<a th:text="#{tablas.menu.${menu.nombre}}"></a>
</li>
For each "menu in ${menus}", menu.nombre has the values paises, regiones, anhos...
But thymeleaf doesn't recognise the model variable inside the #{}, and this it is giving me in the view the error when it doesn't find the message:
??tablas.menu.${menu.nombre}_es_ES??
Configuration is ok, if I change the call for #{tablas.menu.regiones} I get 'regiones' and so.
Is there any way to call a message from messages.properties dynamically using a model variable like this?
Thanks.
You can use the #messages utility object for this:
<a th:text="${#messages.msg('tablas.menu.' + menu.nombre)}" />
Or you can create the string using literal substitution:
<a th:text="#{|tablas.menu.${menu.nombre}|}" />
I would recommend using preprocessing only as a last resort, as bad values can cause runtime errors. (Although they do work for this.)
I am trying to access the responseText on a failure ajax call using formRemote
<g:remoteLink controller="answer" action="delete" id="${answer.id}" update="questions" onFailure="handleError(response)" onComplete="assingActionTestElems()"></g:remoteLink>
But response is not defined, getting this error in FireBug
ReferenceError: response is not defined
This is one of my multiple ajax handling error in the controller
render(status: 500, text: message(code: 'edition.answer.delete.pending'))
¿How can I access to the text message?
I found the solution. It´s easy but not documented. There are 3 fields implicited when a error is thrown, and this is the method to access to them:
onFailure="handleError(XMLHttpRequest,textStatus,errorThrown)"
var handleError = function(XMLHttpRequest,textStatus,errorThrown){
alert(XMLHttpRequest.responseText);
}
You can use just one or all, as needed!
I tried to create a custom data annotation validation attribute (NameValidationAttribute) in MVC 5 project using VS2013. I was able to successfully add the client side validation and the error message for custom validation is getting displayed as soon as the focus leaves the textbox. However, the standard attributes like [Required] and [Range] validators are now not showing proper error messages, says 'Warning: No message defined for 'field' ' (See below screenshot).
Question:
- Why the standard validation error messages are showing as "Warning: No message defined for UnitsInStock"? What am I missing?
Below is my custom client validation script:
I included following scripts in EditProducts page.
Please note that the error messages for UnitPrice, UnitsInStock and ReorderLevel fields are defined with Range validation attribute (see below).
FYI, I tried to change the order of the scripts in ProductEdit page but still its showing the same message.
Please advise!
I ran into this issue. I had created an MVC attribute called PasswordAttribute, with a client side validator called 'password'.
$.validator.addMethod('password', function (value, element, params) {
...[validation logic]
});
$.validator.unobtrusive.adapters.addBool('password');
As soon as I added this logic to the solution I got the error you saw on my Password and ConfirmPassword fields. Note that this occurred before the attribute was even used. Simply renaming the client side validator to 'passwordcheck' fixed the issue. I initially thought that the name 'password' possibly clashed with one of the pre-defined validators (cf. jQuery Validation Documentation) but this doesn't appear to be the case. I suspect now that it is a clash with the name or value for some input field attribute. Anyway, the solution was simply to rename the validator.
jQuery unobtrusive need data-msg for default validate message.
This is how to apply dynamic error message from your model to Html
$.validator.unobtrusive.adapters.add("requireif", function (options) {
$('#' + options.element.id).attr("data-msg", options.message);
// Add rule ...
});
You can change default warning message.
$.validator.addMethod("requireif", function (value, element, pair) {
// validate logic
return true/false;
}, "YOUR DEFAULT MESSAGE HERE");
Or
#Html.TextBoxFor(m => m.Property1, new { Class = "form-control", data_msg = "YOUR DEFAULT MESSAGE HERE" })
Or if you can put it directly to your Html like this.
<input class="form-control" data-msg="YOUR DEFAULT MESSAGE HERE"/>
I'm trying to display a partial view using a custom helper method. The only problem is, I can't get past this syntax issue. The model set for this cshtml file is an IEnumerable collection of models I've defined as Operation. I'm sure this is an easy fix. Here's an example of what I'm seeing:
I have this block of code:
#using(Html.BeginForm()) {
<div id="editor_rows">
#foreach (var item in Model){
Html.RenderPartial("OperationEditorRow", item);
}
</div>
}
This gives me the following error at runtime:
Unexpected "{" after "#" character. Once inside the body of a code block (#if {}, #{}, etc.) you do not need to use "#{" to switch to code.
But if I remove the # sign in front of the foreach statement, everything is interpreted as plain text. So I tried placing an # in front of Html as follows:
#using(Html.BeginForm()) {
<div id="editor_rows">
#foreach (var item in Model){
#Html.RenderPartial("OperationEditorRow", item);
}
</div>
}
This comes back with a compilation error that says:
Cannot implicitly convert type void to object
If I run the project from here, I get a runtime error that says:
The best overloaded method match for 'System.Web.WebPages.WebPageExecutingBase.Write(System.Web.WebPages.HelperResult)' has some invalid arguments
I'm assuming this is related to the previous error. If anybody has a suggestion for me, please help.
Problem solved. I worked on this with a coworker. It turns out the error refferring to the write method pointed to a problem inside my partial view. I was using #{} around a block of code inside of there, which was most likely throwing the other syntax errors also. Thanks for the responses.
Add {}'s around your render call like #{RenderPartial...}
I have the following doubt. I am considering the option to have html tags within my resx texts for localization.
When I put the resources directly I can resort to:
#Html.Raw(#Resources.ResourcesFM.Error_Email)
and it works as expected.
The problem is when the resource is being called by a validation message from an htmlhelper:
#Html.ValidationMessageFor(model => model.Email)
Got from an attibute:
[DataType(DataType.EmailAddress,
ErrorMessageResourceType = typeof(ResourcesFM),
ErrorMessageResourceName = "ErrorMailIncorr")]
What I am trying...
#Html.Raw(Html.ValidationMessageFor(model => model.Email))
I do not know how to get the same result as when using #html.Raw as the output from the helper is a MvcHtmlString...
Thanks
Try this:
View:
#Html.Raw(Server.HtmlDecode(#Html.ValidationMessageFor(m => m.UserName).ToString()))
Controller Action:
ModelState.AddModelError("UserName", "This is a link <a href='http://example.com'>Google Home</a>");
Html.ValidationMessageFor html-encodes the message. But you should be able to simply call HttpUtility.HtmlDecode() on the result. Even though the result contains html tags and whatnot, the decode will simply no-op on that part of the string.
So if `Html.ValidationMessageFor(...)' returns
<span><div>This is in a div</div<></span>
Then HttpUtility.HtmlDecode(Html.ValidationMessageFor(...).ToString()) will give you
<span><div>This is in a div</div></span>
It's not pretty, but it works. Your alternative is to recreate your own Validation helper version that never encodes the message.
For Localization, you may use String.Format and choose appropriate placeholder for the link
ModelState.AddModelError("UserName", String.Format("This is a link {0}", "<a href='http://example.com'>Appropriate String From a Resource</a>"));