How to get values of several form elements and send them to controller with vue.js? - laravel

I am learning Laravel 5.2 and vue.js,and not familiar with the grammars,the question is:
How to get all of the values of the form elements below and send them to controller with vue.js?
Including text,select,textarea,file input,radios,checkboxes.
PS:
There is a plugin in the html demo,it's function is compressing a selected image.
lrz.bundle.js,https://github.com/think2011/localResizeIMG
html demo:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.2/css/bootstrap.min.css" integrity="sha384-y3tfxAZXuh4HwSYylfB+J125MxIs6mR5FOHamPBG064zB+AFeWH94NdvaCBm8qnd" crossorigin="anonymous">
</head>
<body>
<div class="container">
<form>
<div class="form-group row">
<label for="formGroupExampleInput" class="col-sm-2 form-control-label">Text</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="formGroupExampleInput" placeholder="">
</div>
</div>
<div class="form-group row">
<label for="exampleSelect1" class="col-sm-2 form-control-label">Select</label>
<div class="col-sm-10">
<select class="form-control" id="exampleSelect1">
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
<option>5</option>
</select>
</div>
</div>
<div class="form-group row">
<label for="exampleTextarea" class="col-sm-2 form-control-label">Textarea</label>
<div class="col-sm-10">
<textarea class="form-control" id="exampleTextarea" rows="3"></textarea>
</div>
</div>
<div class="form-group row">
<label for="exampleInputFile" class="col-sm-2 form-control-label">File input</label>
<div class="col-sm-10">
<input id="exampleInputFile" name="photo" type="file" class="form-control-file" value="Upload" accept="image/*">
preview:
<img id="preview"/>
</div>
</div>
<div class="form-group row">
<label class="col-sm-2">Radios</label>
<div class="col-sm-10">
<label class="radio-inline">
<input type="radio" name="inlineRadioOptions" id="inlineRadio1" value="option1"> 1
</label>
<label class="radio-inline">
<input type="radio" name="inlineRadioOptions" id="inlineRadio2" value="option2"> 2
</label>
<label class="radio-inline">
<input type="radio" name="inlineRadioOptions" id="inlineRadio3" value="option3"> 3
</label>
</div>
</div>
<div class="form-group row">
<label class="col-sm-2">Checkboxes</label>
<div class="col-sm-10">
<div class="checkbox">
<label class="checkbox-inline">
<input type="checkbox" id="inlineCheckbox1" value="option1"> 1
</label>
<label class="checkbox-inline">
<input type="checkbox" id="inlineCheckbox2" value="option2"> 2
</label>
<label class="checkbox-inline">
<input type="checkbox" id="inlineCheckbox3" value="option3"> 3
</label>
</div>
</div>
</div>
<div class="form-group row">
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" class="btn btn-secondary">Submit</button>
</div>
</div>
</form>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.2/js/bootstrap.min.js" integrity="sha384-vZ2WRJMwsjRMW/8U7i6PWi6AlO1L79snBrmgiDpgIWJ82z8eA5lenwvxbMV1PAh7" crossorigin="anonymous"></script>
<script src="js/dist/lrz.bundle.js"></script>
<script>
$(function () {
var $preview = $('#preview');
$('#exampleInputFile').on('change', function () {
lrz(this.files[0], {
width: 800
}).then(function (rst) {
$preview.attr('src', rst.base64);
rst.formData.append('fileLen', rst.fileLen);
});
});
});
</script>
</body>
</html>

I've a little bit of uncertainty as to whether or not it's actually a Laravel -> Vue setup you're looking for since you have absolutely no Laravel nor Vue code in your question which is extremely broad, but here's a basic template to get started. I use the following in pretty much every project.
Laravel
Create your route - routes/web.php:
Route::post('/myform', 'FormControntroller#submitForm');
Create your controller and method - app/http/controllers/FormController.php
class FormController extends App\Controllers\Controller {
public function submitForm()
{
var_dump(request->all());
}
}
Create your entry view - resources/views/app.blade.php
<html>
<head>
<title>Minimal Vue Example</title>
</head>
<body>
<div id="app">
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/1.0.1/vue.min.js"></script>
<script src="/js/main.js"></script
</body>
</html>
Vue
main.js
import Vue from 'vue'
import Resource from 'vue-resource'
import Router from 'vue-router'
import Root from './components/Root.vue'
Vue.use(Router)
Vue.use(Resource)
var router = new Router({
history: true,
});
router.map({
'/': {
component: Root
},
});
// Start up our app
router.start(Root, '#app');
Create your root component - resources/views/assets/js/components/Root.vue
<template>
<form v-on:submit.prevent="submitForm">
<input type="text" v-model="formData.username"/>
<input type="text" v-model="formData.password"/>
</form>
</template>
<script>
export default {
data: function() {
return {
formData: {
username: null,
password: null
}
}
},
methods: {
submitForm: function() {
this.$http.post('/myform', this.formData).then(function(response) {
alert('Yay, my form was posted!');
});
}
}
}
</script>
At this point you'll need to run webpack on your assets, see the Laravel Documentation on Elixir.
Again, you've asked a very broad question without providing much background, but this will get you going.
Notes: The above code is working code on Vue 1.X, version 2 is slightly different.
For further help on Vue and Laravel, see the Laravel Documentation.

Related

Partial View rendered in modal via ajax missing javascript events

Im having issues when placing html content from partial view into modal content via ajax, not all events defined in _layout.cshtml are being attached to elements in modal content.
Setup:
_Layout.cshtml
<!DOCTYPE html>
<html lang="en">
<head>
//custom css is here.
</head>
<body>
#RenderBody()
<partial name="_Modals" /> <-- all variations of modals exist in this file
//custom javascript files <-- **this is failing to attached to modal content**
#RenderSection("CustomScriptsSection", false);
</body>
</html>
_CustomLayout.cshtml
#{
Layout = "~/Views/Shared/_Layout.cshtml";
}
<partial name="_SideBar" />
<main>
<partial name="_NavBar" />
<div>
#RenderBody()
<partial name="_Footer" />
</div>
</main>
#section CustomScriptsSection{
#RenderSection("Scripts", false)
}
_Viewstart.cshtml
#{
Layout = "~/Views/Shared/_CustomLayout.cshtml";
}
The Ajax Call snippet from a standard razor view(not a page).
#section Scripts{
$('#DefaultModelBtn').on('click', function (e) {
var RegisterURLPartial = "/Home/RegisterPartial"
$('#modal-default').modal('show');
$('#modal-default').off('shown.bs.modal').on('shown.bs.modal', function () {
if ($('#PartialContainer').length) {
$('#PartialContainer').load(RegisterURLPartial, function (response, status, xhr) {
});
}
});
});
}
Controller Method for the Partial Page
public virtual IActionResult RegisterPartial() => PartialView("~/Views/Home/Partial/_Register.cshtml");
The partial Page itself (ambiguous Action, Id, and Controller names)
<form id="someId" asp-action="someAction" asp-controller="someController" method="post">
<div class="input-group input-group-outline mb-3">
<label asp-for="Name" class="form-label"></label>
<input asp-for="Name" type="text" class="form-control" autocomplete="off">
</div>
<div class="input-group input-group-outline mb-3">
<label asp-for="Email" class="form-label"></label>
<input asp-for="Email" type="email" class="form-control" autocomplete="off">
</div>
<div class="input-group input-group-outline mb-3">
<label asp-for="Password" class="form-label"></label>
<input asp-for="Password" type="password" class="form-control" autocomplete="off">
</div>
<div class="text-center">
<button type="submit" class="btn btn-lg bg-gradient-primary btn-lg w-100 mt-4 mb-0">Sign Up</button>
</div>
</form>
What I noticed was the css is being formatted properly, but the javascript that attaches to those css class are not working, eg. focus event is missing in the modal. (input-group-outline css class is missing focus event)
No Razor Pages are used at all (#page not used).
Thanks for the help guys.

Auto Age Calculation Field View In Html Form

I am trying to auto calculate the field for age in my asp.net mvc form and post it to the form. I am using datetimepicker to derive the date of birth. Does anyone know how to calculate it just by using the date of birth and post it straight to the forms? Here is my view:
<script language="javascript">
$(document).ready(function () {
// DateA
$('#JSDateA')
.datetimepicker({ format: 'YYYY-MM-DD' });
<form asp-controller="Admin" asp-action="Edit"
method="post">
<div class="form-group row">
<div class="offset-sm-2 col-sm-5 ">
Update User
</div>
</div>
<div class="form-group row">
<label class="control-label col-sm-2" asp-for="Dob">Birth Date :</label>
<div class="col-sm-5">
<input asp-for="Dob" asp-format="{0:yyyy-MM-dd}"
class="form-control" placeholder="YYYY-MM-DD" />
</div>
#{
// TODO: L09 Task 4d - Validation Message for Dob
}
</div>
<div class="form-group row">
<label class="control-label col-sm-2" for="Age">Age :</label>
<div class="col-sm-5">
<input type="text" id="age" asp-for="Age" class="form-control" />
</div>
</div>
<div class="form-group row">
<div class="offset-sm-2 col-sm-6">
<input type="submit" value="Update" class="btn btn-primary" />
</div>
</div>
#if (ViewData["Message"] != null)
{
<div class="form-group row">
<div class="offset-sm-2 col-sm-6">
<div class="alert alert-#ViewData["MsgType"]">
#Html.Raw(ViewData["Message"])
</div>
</div>
</div>
}
</form>
You can calculate age using js. By setting change event, calculate date and put it to age text field. Try this
$(document).ready(function(){
$("#txtDOB").change(function(){
var dob = $("#txtDOB").val();
if(dob != null || dob != ""){
$("#age").val(getAge(dob));
}
});
function getAge(birth) {
ageMS = Date.parse(Date()) - Date.parse(birth);
age = new Date();
age.setTime(ageMS);
ageYear = age.getFullYear() - 1970;
return ageYear;
}
});
Here is a example fiddle for you.
Before resolve your issue,you need know the following things:
1.If Dob in your model is type of DateTime,it will generate <input type="date">,you need set the html type="text",otherwise you will have two datepicker,one belongs to jquery ui,the other belongs to the default html5 datepicker.
2.jquery set input text value by using val().
3.You do not have any html element which has id="JSDateA",so what you did will never work.
Working Demo:
Model:
public class TestVM
{
public DateTime Dob { get; set; }
public int Age { get; set; }
}
View:
<form asp-controller="Admin" asp-action="Edit"
method="post">
<div class="form-group row">
<div class="offset-sm-2 col-sm-5 ">
Update User
</div>
</div>
<div class="form-group row">
<label class="control-label col-sm-2" asp-for="Dob">Birth Date :</label>
<div class="col-sm-5">
<input asp-for="Dob" asp-format="{0:yyyy-MM-dd}"
class="form-control" placeholder="YYYY-MM-DD" type="text" />
#*add type="text"*#
</div>
<div class="form-group row">
<label class="control-label col-sm-2" for="Age">Age :</label>
<div class="col-sm-5">
<input type="text" id="age" asp-for="Age" class="form-control" />
</div>
</div>
<div class="form-group row">
<div class="offset-sm-2 col-sm-6">
<input type="submit" value="Update" class="btn btn-primary" />
</div>
</div>
#if (ViewData["Message"] != null)
{
<div class="form-group row">
<div class="offset-sm-2 col-sm-6">
<div class="alert alert-#ViewData["MsgType"]">
#Html.Raw(ViewData["Message"])
</div>
</div>
</div>
}
</div>
</form>
The first way,you could write js like below(by using jquery UI Datepicker Widget):
#section Scripts{
<link rel="stylesheet" href="https://code.jquery.com/ui/1.12.1/themes/smoothness/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script language="javascript">
$(document).ready(function () {
$('#Dob')
.datepicker({
format: 'yyyy-MM-DD',
maxDate: '+0d',
yearRange: '1950:2021',
changeMonth: true,
changeYear: true,
onSelect: function (value, ui) {
var today = new Date(),
dob = new Date(value),
age = new Date(today - dob).getFullYear() - 1970;
$('#age').val(age);
}
});
})
</script>
}
Result:
The second way,you could write js like below(by using bootstrap-datetimepicker):
#section Scripts
{
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.15.1/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.7.14/js/bootstrap-datetimepicker.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.7.14/css/bootstrap-datetimepicker.min.css">
<script>
$(function () {
$('#Dob').datetimepicker();
$('#Dob').on('dp.change', function (e) {
var value = e.date.format(e.date._f);
var today = new Date(),
dob = new Date(value),
age = new Date(today - dob).getFullYear() - 1970;
$('#age').val(age);
})
});
</script>
}
Result2:

How to submit Laravel VueJS dynamic form data?

I am new to Vue.js. I am trying to make a form dynamic (only a certain part of the form dynamic.). A user can have multiple guarantors. So I made the Guarantor form Dynamic with VueJS. When I submit the form and return the request, I see only the last array. Its always the last array, all others are lost.
This is the blade file.
<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="{{ asset('css/app.css')}}">
<title>Laravel</title>
</head>
<body>
<div id="app">
<div class="container pt-5">
<form action="{{ route('submit.store')}}" method="post">
#csrf
<div class="card-body">
<h4 class="card-title">User Detail</h4>
<input type="text" class="form-control mb-1" name="user_name" id="user_name" placeholder="Name" />
<input type="email" class="form-control mb-1" name="user_email" id="user_email"
placeholder="Email" />
<textarea name="about" class="form-control" id="about" cols="30" rows="10"
placeholder="About"></textarea>
</div>
<dynamic-form></dynamic-form>
</form>
</div>
</div>
<script src="{{ asset('js/app.js') }}"></script>
</body>
</html>
And this is how the VueComponent looks.
<template>
<div>
<button class="btn btn-success mb-3" #click.prevent="addNewUser">Add User</button>
<div class="card mb-3" v-for="(user, index) in users" :key="index">
<div class="card-body">
<span class="float-right" style="cursor:pointer" #click.prevent="removeForm(index)" >X</span>
<h4 class="card-title">Guarantor No: {{ index }}</h4>
<input type="text" class="form-control mb-1" name="name" id="name" placeholder="Name" v-model="user.name" />
<input type="email" class="form-control mb-1" name="email" id="email" placeholder="Email" v-model="user.email"/>
<textarea name="about" class="form-control" id="about" cols="30" rows="10" placeholder="About" v-model="user.about"></textarea>
</div>
</div>
<input type="submit" class="btn btn-primary" value="submit">
</div>
</template>
<script>
export default {
name: 'dynamic-form',
data() {
return{
users: [
{
name: '',
email: '',
about: ''
}
]
}
},
methods: {
addNewUser: function() {
this.users.push({
name: '',
email: '',
about: ''
});
},
removeForm: function(index) {
this.users.splice(index, 1);
}
}
}
</script>
How can I tackle this problem?
In PHP, values with the same name attribute value will get overwritten. (See the "How do I get all the results from a select multiple HTML tag?" section here).
You can create arrays of values by adding a bracket to the name. For example, if you made the name of the "name" input name[], name will be an array of names in PHP.
In your case, you could use this format: name="guarantors[][name]". That way you will get an array in PHP under the key guarantors (e.g. $request->guarantors) and each of the values in guarantors will be an array with the values name, email, etc.

How to get Ckeditor textarea value in laravel

i am using Ckeditor for blog posting in my project when i submit the form nothing i am get in controller can any one suggest me solution for that.
my view is looking like
<div class="container">
<div class="row">
<div class="col-md-10 col-md-offset-2">
<div class="panel panel-default">
<div class="panel-heading">Post</div>
<div class="panel-body">
<form class="form-horizontal" role="form" method="POST" action="{{ route('store-post') }}">
{{ csrf_field() }}
<div class="form-group">
<label for="category_id" class="col-md-2 control-label">Select Categories</label>
<div class="col-md-8">
<select class="form-control" id="category_id" name="category_id">
#foreach($categories as $category)
<option value="{{$category->url_name}}">
{{$category->category_name}}</option>
#endforeach
</select>
</div>
</div>
<div class="form-group">
<label for="email" class="col-md-2 control-label">Post Title</label>
<div class="col-md-8">
<input id="post_title" type="text" class="form-control" name="post_title" value="{{ old('post_title') }}">
</div>
</div>
<div class="form-group">
<label for="post_content" class="col-md-2 control-label">Post Description</label>
<div class="col-md-8">
<textarea id="post_content" rows="10" cols="60" class="span8" placeholder="Image Title Goes Here" name="post_content"></textarea>
</div>
</div>
<div class="form-group">
<label for="p_url" class="col-md-2 control-label">Post Url</label>
<div class="col-md-8">
<input id="p_url" type="text" class="form-control" name="p_url" value="{{ old('p_url') }}">
</div>
</div>
<div class="form-group">
<label for="p_title" class="col-md-2 control-label">Meta Title</label>
<div class="col-md-8">
<input id="p_title" type="text" class="form-control" name="p_title" value="{{ old('p_title') }}">
</div>
</div>
<div class="form-group">
<label for="p_keyword" class="col-md-2 control-label">Meta Keyword</label>
<div class="col-md-8">
<input id="p_keyword" type="text" class="form-control" name="p_keyword" value="{{ old('p_keyword') }}">
</div>
</div>
<div class="form-group">
<label for="email" class="col-md-2 control-label">Meta Description</label>
<div class="col-md-8">
<textarea class="form-control" id="p_mdesc" name="p_mdesc" rows="3">
</textarea>
</div>
</div>
<div class="form-group">
<div class="col-md-8 col-md-offset-2">
<button type="submit" class="btn btn-primary">
Submit
</button>
</div>
</div>
<!--Error start-->
#if ($errors->any())
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
<!--error ends-->
</form>
</div>
</div>
</div>
</div>
</div>
my controller code is
public function store(Request $request){
/*$this->validate($request, [
'category_id' => 'required',
'post_title' => 'required',
//'post_content' => 'required',
'p_url' => 'required',
'p_title' => 'required',
'p_keyword' => 'required',
'p_mdesc' => 'required',
]);*/
$post=new Post;
echo $post_content=$request->input('post_content');
}
in previous project ie designed in CI i just use
$tc=$this->input->post('tc'); in controller for getting the Ckeditor value but in laravel i am not sure how to get it done.
Your view contain 2 name attribute for the post_content field (textarea). Please check.
You can do it like this -
{!! Form::textarea('tc', $tc,array('required', 'class'=>'form-control', placeholder'=>'Your message')) !!}
and then you will have to initialise it
$(document).ready(function () {
CKEDITOR.replace( 'tc' );
});
The documentation has clear examples.
In your Blade you should add ckeditor like this:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>A Simple Page with CKEditor</title>
<!-- Make sure the path to CKEditor is correct. -->
<script src="../ckeditor.js"></script>
</head>
<body>
<form>
<textarea name="editor1" id="editor1" rows="10" cols="80">
This is my textarea to be replaced with CKEditor.
</textarea>
<script>
// Replace the <textarea id="editor1"> with a CKEditor
// instance, using default configuration.
CKEDITOR.replace( 'editor1' );
</script>
</form>
</body>
</html>
So the javascript code triggers a replace of a textarea to the editor
Now for the retrieving data part
<script>
var data = CKEDITOR.instances.editor1.getData();
// Your code to save "data", usually through Ajax.
</script>
You need to create an endpoint if you want to send this data indeed trough Ajax. Don't forget to add a CSRF token
As mentioned by #user3888958,
<textarea name="tc" id="post_content" rows="10" cols="60"
class="span8" placeholder="Image Title Goes Here" name="post_content">
the textarea has two name attribute.
You could access the textarea content using the name attribute, remove any one name attribute and pass that in as a parameter to the request
$request->input('tc'); // OR
$request->input('post_content');
and to access the value of
<textarea class="form-control" id="p_mdesc" name="p_mdesc" rows="3">
</textarea>
you could access it using the name
$request->input('p_mdesc');

How to show a beanValidation class level constraint on a thymeleaf view?

I'm using bean validation(JSR303) to validate two fields, those fields are validate with an annotation and a validator, the annotation targeted the type that means the annotation is a class level constraint of my bean.
The question is how do I express the error on my view?
(I'm using groovy)
SignupForm :
package core.model
import core.validation.PasswordConfirmation
import core.validation.UniqueEmail
import core.validation.UniqueUsername
import groovy.util.logging.Slf4j
import org.hibernate.validator.constraints.Email
import org.hibernate.validator.constraints.NotBlank
import static core.model.AuthoritiesEnum.ROLE_USER
#Slf4j
#PasswordConfirmation
class SignupForm {
static final String NOT_BLANK_MESSAGE = "{notBlank.message}"
static final String UNIQUE_USERNAME_MESSAGE = "{uniqueUsername.message}"
static final String EMAIL_MESSAGE = "{username.message}"
static final String UNIQUE_EMAIL_MESSAGE = "{uniqueEmail.message}"
#UniqueUsername
#NotBlank(message = SignupForm.NOT_BLANK_MESSAGE)
String username
#UniqueEmail
#NotBlank(message = SignupForm.NOT_BLANK_MESSAGE)
#Email(message = SignupForm.EMAIL_MESSAGE)
String email
#NotBlank(message = SignupForm.NOT_BLANK_MESSAGE)
String password
#NotBlank(message = SignupForm.NOT_BLANK_MESSAGE)
String confirmPassword
User createAccount() {
new User(username: email, email: email, password: password, role: ROLE_USER)
}
}
PasswordConfirmation validation annotation :
package core.validation
import javax.validation.Constraint
import javax.validation.Payload
import java.lang.annotation.Retention
import java.lang.annotation.Target
import static java.lang.annotation.ElementType.TYPE
import static java.lang.annotation.RetentionPolicy.RUNTIME
#Target(TYPE)
#Retention(RUNTIME)
#Constraint(validatedBy = PasswordConfirmationValidator)
#interface PasswordConfirmation {
String message() default "{core.signup.validation.passwordConfirmation.message}"
Class<?>[] groups() default []
Class<? extends Payload>[] payload() default []
}
Password confirmation validator :
package core.validation
import core.model.SignupForm
import groovy.util.logging.Slf4j
import javax.validation.ConstraintValidator
import javax.validation.ConstraintValidatorContext
#Slf4j
class PasswordConfirmationValidator implements ConstraintValidator<PasswordConfirmation, SignupForm> {
#Override
void initialize(PasswordConfirmation constraintAnnotation) {
}
#Override
boolean isValid(SignupForm form, ConstraintValidatorContext context) {
log.info "password : ${form.password}"
log.info "confirmPassword : ${form.confirmPassword}"
println "password : ${form.password}"
println "confirmPassword : ${form.confirmPassword}"
println "defaultConstraintMessageTemplate : ${context.defaultConstraintMessageTemplate}"
form.password.equals form.confirmPassword
}
}
the thymeleaf view signup.html :
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">
<head>
<title th:text="#{view.signup.title}">Inscription</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<link href="../../../resources/css/bootstrap.min.css" rel="stylesheet" media="screen"
th:href="#{/resources/css/bootstrap.min.css}"/>
<link href="../../../resources/css/core.css" rel="stylesheet" media="screen" th:href="#{/resources/css/core.css}"/>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script src="../../../resources/js/bootstrap.min.js" th:src="#{/resources/js/bootstrap.min.js}"></script>
</head>
<body>
<div th:replace="fragments/header_signup :: header">Header</div>
<form class="form-narrow form-horizontal" method="post"
th:action="#{/signup}" th:object="${signupForm}">
<!-- /* Show general error message when form contains errors */ -->
<th:block th:if="${#fields.hasErrors('${signupForm.*}')}">
<div th:replace="fragments/alert :: alert (type='danger', message='Form contains errors. Please try again.')">
Alert
</div>
</th:block>
<fieldset>
<div class="form-group" th:classappend="${#fields.hasErrors('username')}? 'has-error'">
<label for="username" class="col-lg-2 control-label">Username</label>
<div class="col-lg-10">
<input type="text" class="form-control" id="username" placeholder="Username" th:field="*{username}"/>
<span class="help-block" th:if="${#fields.hasErrors('username')}"
th:errors="*{username}">Incorrect username</span>
</div>
</div>
<div class="form-group" th:classappend="${#fields.hasErrors('email')}? 'has-error'">
<label for="email" class="col-lg-2 control-label">Email</label>
<div class="col-lg-10">
<input type="text" class="form-control" id="email" placeholder="Email address" th:field="*{email}"/>
<span class="help-block" th:if="${#fields.hasErrors('email')}"
th:errors="*{email}">Incorrect email</span>
</div>
</div>
<div class="form-group" th:classappend="${#fields.hasErrors('password')}? 'has-error'">
<label for="password" class="col-lg-2 control-label">Password</label>
<div class="col-lg-10">
<input type="password" class="form-control" id="password" placeholder="Password"
th:field="*{password}"/>
<span class="help-block" th:if="${#fields.hasErrors('password')}" th:errors="*{password}">Incorrect password</span>
</div>
</div>
<div class="form-group" th:classappend="${#fields.hasErrors('confirmPassword')}? 'has-error'">
<label for="confirmPassword" class="col-lg-2 control-label">Password confirmation</label>
<div class="col-lg-10">
<input type="password" class="form-control" id="confirmPassword" placeholder="Password confirmation"
th:field="*{confirmPassword}"/>
<!--how to show classe level constraint validation-->
<span class="help-block" th:if="${#fields.hasErrors('confirmPassword')}" th:errors="*{confirmPassword}">Incorrect password confirmation</span>
</div>
</div>
<div class="form-group">
<div class="col-lg-offset-2 col-lg-10">
<button type="submit" class="btn btn-default" th:text="#{view.signup.label}">Sign up</button>
</div>
</div>
</fieldset>
</form>
</body>
</html>
In order to show a class level constraint message I succeeded by using the global constant, like in the updated html code as shown in the documentation
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">
<head>
<title th:text="#{view.signup.title}">Inscription</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<link href="../../../resources/css/bootstrap.min.css" rel="stylesheet" media="screen"
th:href="#{/resources/css/bootstrap.min.css}"/>
<link href="../../../resources/css/core.css" rel="stylesheet" media="screen" th:href="#{/resources/css/core.css}"/>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script src="../../../resources/js/bootstrap.min.js" th:src="#{/resources/js/bootstrap.min.js}"></script>
</head>
<body>
<div th:replace="fragments/header_signup :: header">Header</div>
<form class="form-narrow form-horizontal" method="post"
th:action="#{/signup}" th:object="${signupForm}">
<!-- /* Show general error message when form contains errors */ -->
<th:block th:if="${#fields.hasErrors('${signupForm.*}')}">
<div th:replace="fragments/alert :: alert (type='danger', message='Form contains errors. Please try again.')">
Alert
</div>
</th:block>
<fieldset>
<div class="form-group" th:classappend="${#fields.hasErrors('username')}? 'has-error'">
<label for="username" class="col-lg-2 control-label">Username</label>
<div class="col-lg-10">
<input type="text" class="form-control" id="username" placeholder="Username" th:field="*{username}"/>
<span class="help-block" th:if="${#fields.hasErrors('username')}"
th:errors="*{username}">Incorrect username</span>
</div>
</div>
<div class="form-group" th:classappend="${#fields.hasErrors('email')}? 'has-error'">
<label for="email" class="col-lg-2 control-label">Email</label>
<div class="col-lg-10">
<input type="text" class="form-control" id="email" placeholder="Email address" th:field="*{email}"/>
<span class="help-block" th:if="${#fields.hasErrors('email')}"
th:errors="*{email}">Incorrect email</span>
</div>
</div>
<div class="form-group" th:classappend="${#fields.hasErrors('password')}? 'has-error'">
<label for="password" class="col-lg-2 control-label">Password</label>
<div class="col-lg-10">
<input type="password" class="form-control" id="password" placeholder="Password"
th:field="*{password}"/>
<span class="help-block" th:if="${#fields.hasErrors('password')}" th:errors="*{password}">Incorrect password</span>
</div>
</div>
<div class="form-group" th:classappend="${#fields.hasErrors('confirmPassword')}? 'has-error'">
<label for="confirmPassword" class="col-lg-2 control-label">Password confirmation</label>
<div class="col-lg-10">
<input type="password" class="form-control" id="confirmPassword" placeholder="Password confirmation"
th:field="*{confirmPassword}"/>
<span class="help-block" th:if="${#fields.hasErrors('confirmPassword')}" th:errors="*{confirmPassword}">Incorrect password confirmation</span>
<span class="help-block" th:if="${#fields.hasErrors('global')}" th:errors="*{global}">Incorrect password confirmation</span>
</div>
</div>
<div class="form-group">
<div class="col-lg-offset-2 col-lg-10">
<button type="submit" class="btn btn-default" th:text="#{view.signup.label}">Sign up</button>
</div>
</div>
</fieldset>
</form>
</body>
</html>

Resources