Thymeleaf: validation error by field - spring

Using Thymeleaf + Spring and form validation, I want to display errors that are related to a field next to this field.
<input type="text"
th:field="*{companyName}" class="form-control"
placeholder="Code client" th:errorClass="'error'"/>
If the field has an error, the class "error" is applied indeed. But is there an easy way to display also the validation error of the field?

Use this code to display error:
<p class="alert alert-danger" th:if="${#fields.hasErrors('companyName')}" th:errors="*{companyName}"></p>

Related

Thymeleaf + Spring. Using an object method instead another block in the form

I have a typical updateUser form built with Thymeleaf + Spring. I can list the user roles but I am trying to put these into a selectbox component. I am struggling with this line th:selected="${user.hasRole(role.role)}". Now, I know this component works and that is only a matter of access a boolean function to enable it. I am trying to reference a function of the form object using the select th:object. My syntax doesn't work. I have also try to access that function just like previous input tags would (only using the name without the object itself .ie username or in this case hasRole(). That doesn't work either.
<form th:object="${user}"
th:action="#{'/admin/usermanagement/adduser'} " method="post">
<div class="row">
<div class="col-md-3 form-group">
<label>Username:</label> <input type="text" class="form-control"
th:field="*{username}" />
</div>
</div>
<div class="col-md-3">
<h5>Roles :</h5>
</div>
<select class="js-example-basic-multiple" style="width: 75%"
name="froles" id="froles" multiple="multiple">
<option th:each="role : ${roles}" th:value="${role.role}"
th:selected="${user.hasRole(role.role)}"
th:text="${role.role}"></option>
</select>
<button type="submit" class="btn btn-primary">Submit</button>
In fact, my problem is types. th:selected="${user.hasRole(role.role)}" is a string and should be th:selected="${user.hasRole(role)}". I have both method in the domain object so that is fine.
th:value="${role.role}" is wrong for persistence. I want to return role but I get the following error message when I use role.role
codes [user.roles,roles]; arguments []; default message [roles]]; default message [Failed to convert property value of type 'java.lang.String' to required type 'java.util.List' for property
and Java null exception when I use "${role}"

vee-validate error message don't have the field name

I am trying to get a hand of vee-validate 3. A lot has changed on version 3.
Problem is the error messages do not have the specific field name. Below is the code that i have in a laravel blade file:
<validation-provider rules="email" v-slot="{ errors }">
<input type="text"
class="input"
name="email"
v-model="email">
<span>#{{ errors[0] }}</span>
</validation-provider>
When i strart typing in the input field, the error message prints inside the span tags, but it does not have the field name, rather a generic 'field', such as below:
{field} is not valid.
Anybody knows how to get this working?
Thanks,
I found it in the docs. All you need to do is add a name property to the validation-provider component like below:
<validation-provider rules="email" name="...add_input_field_name_here..." v-slot="{ errors }">

Thymeleaf: How to use fragment parameter in expressions

Is there a way to use a fragment parameter in an expression?
I'd like to create a fragment to show fields with their corresponding binding errors e.g. like:
<div th:fragment="alert (field, fieldLabel)">
<label><span th:text="${fieldLabel}">Label:</span><input type="text" th:errorclass="field_error" th:field="*{field}"/></label>
<div th:if="${#fields.hasErrors(field)}"><span th:errors="*{field}">Some error</span></div>
</div>
Getting the fragment with:
<div th:replace=":: alert (field='firstName', fieldLabel='Firstname')">Field</div>
How do I use the field parameter in the expressions for the th:field and th:errors attributes? *{field} does at least not work.
With Thymeleaf 2.1 I've been using the following:
Declare field:
<input type="password" th:field="*{password}" />
Show possible errors related to password:
<div th:replace="util/form :: field-errors('password')"></div>
And this prints all the errors related to given field:
<div class="error-container help-block"
th:fragment="field-errors(field)"
th:if="${#fields.hasErrors('__${field}__')}">
<ul>
<li th:each="error : ${#fields.errors('__${field}__')}"
th:text="${error}" />
</ul>
</div>
It seems that it is not possible at least
using th:field and th:errors, it keeps trying to look for a bean instead
of the parameter of the fragment.
Try setting a local variable for the DOM object
th:with="variableName=${field}"
An then try to use that variable in the expressions.

How to update Angular validation messages after $http response?

I'm using Angular $http (http://docs.angularjs.org/api/ng.$http) to submit a form. The server returns JSON:
[{
"hasValidationErrors": true,
"validationErrors": {
"inputNameAttributeValue": "Error Message 1",
"anotehrInputNameAttributeValue": "Error Message 2"
}
}]
Once I receive the JSON response, how do I notify Angular that certain form fields are in an error state so that it automatically changes the view to show error messages?
For example, if I use this markup (from http://www.ng-newsletter.com/posts/validations.html):
<div class="row">
<div class="large-12 columns">
<label>Your name</label>
<input type="text"
placeholder="Name"
name="inputNameAttributeValue"
ng-model="signup.name"
ng-minlength=3
ng-maxlength=20 required />
<div class="error"
ng-show="signup_form.name.$dirty && signup_form.name.$invalid">
<small class="error"
ng-show="signup_form.name.$error.required">
Your name is required.
</small>
<small class="error"
ng-show="signup_form.name.$error.minlength">
Your name is required to be at least 3 characters
</small>
<small class="error"
ng-show="signup_form.name.$error.maxlength">
Your name cannot be longer than 20 characters
</small>
</div>
</div>
</div>
I'm looking for a solution that works with my existing data binding markup in my html doc.
I can change the markup, but I don't want to have two separate sections of markup for each form input (one for client side validation and another for validation after the JSON response).
Update:
For example, if required form fields have not been touched by the user
before the form is submitted, they will not show error messages. So,
my goal is that upon form submission, all form fields are validated
and show validation messages if needed.
That's because ng-show is triggered by both $dirty and $invalid flag.
You can manually set all $dirty of input fields to true when ngSubmit fired.
But, in the case the user has tampered with the form, the JSON
response from the server should be used to add validation messages as
well.
If validation failed on server, just bring these tampered values back to angular models on client and use $apply if needed. AngularJS should do the rest of work.
Simulating example: http://jsfiddle.net/djpV8/4/
Origin:
how about set error messages to the scope and simply display it when it's defined:
scope.errorMessages = returnedJson.validationErrors;
just add a block for displaying custom message from server
<!-- place error messages next to corresponding input fields. -->
<small class="error"
ng-show="errorMessages.inputName"
ng-bind="errorMessages.inputName"></small>

In Grails, how do I display validation error messages next to the fields?

The Grails 2.0.4 documentation for validation shows you how to display error messages at the top of the page and how to add a css class to an element if a field is invalid, but it doesn't tell you how to display the error message next to the fields themselves, something like this:
-----------------------
Name: | | You must enter a name!
-----------------------
How do you retrieve the specific error message for an invalid field and then display it next to the field it's for?
Actually, the documentation does show how to do this, it just isn't overly clear that this is what they mean:
<g:renderErrors bean="${book}" as="list" field="title"/>
If you specify the field attribute, it will only render error(s) for that field. So then it is just up to you to write the HTML accordingly.
<input type="text" ... /> <g:if test="${bean.hasErrors}"><g:renderErrors bean="${book}" as="list" field="title"/></g:if>
It can get as simple or as complicated as you would like it and while I generally like grails plugins, this just seems simple enough to do without one and you have more control over the markup.
I use the Grails Fields plugin to do this, and it works a treat.
It makes it easy to create default templates for form field rendering. For example I have the following in grails-app/views/_fields/default/_field.gsp:
<%# page defaultCodec="html" %>
<div class="control-group${invalid ? ' error' : ''}">
<label class="control-label" for="${property}${index ?: ""}">${label}</label>
<div class="controls">
<%= widget.replace("id=\"${property}\"", "id=\"${property}${index ?: ""}\"") %>
<g:if test="${invalid}"><span class="help-inline">${errors.join('<br>')}</span></g:if>
</div>
</div>
As you can see from the HTML the errors are displayed inline. Here is part of my login form:
<g:form controller="home" action="login" >
<f:field bean="user" property="email"/>
<f:field bean="user" property="password">
<g:field type="password" name="${property}" value="${value}"/>
</f:field>
</g:form>
Here is the custom error in context, wrapped around username field. This will do what you want.
<dt>User Id</dt>
<dd><g:textField name="username" value="${user?.username}"/>
<g:hasErrors bean="${user}" field="username">
<g:eachError bean="${user}" field="username">
<p style="color: red;"><g:message error="${it}"/></p>
</g:eachError>
</g:hasErrors>
</dd>
I would recommend going with Jquery validation plugin. There's several Grails plugin about this, but they are a bit out-dated. Besides, I think this task is pretty simple for using another plugin.

Resources