Helpers, Data Validation

Slides:



Advertisements
Similar presentations
AngularJS Directives Defining Custom Directives SoftUni Team Technical Trainers Software University
Advertisements

Sets, Dictionaries SoftUni Team Technical Trainers Software University
First Steps in PHP Creating Very Simple PHP Scripts SoftUni Team Technical Trainers Software University
Stacks and Queues Processing Sequences of Elements SoftUni Team Technical Trainers Software University
Version Control Systems
Auto Mapping Objects SoftUni Team Database Applications
Databases basics Course Introduction SoftUni Team Databases basics
C# MVC Frameworks – ASP.NET
Web API - Introduction AJAX, Spring Data REST SoftUni Team Web API
Introduction to MVC SoftUni Team Introduction to MVC
Cookies, Sessions, Bootstrap
Deploying Web Application
Thymeleaf and Spring Controllers
PHP MVC Frameworks Course Introduction SoftUni Team Technical Trainers
PHP Fundamentals Course Introduction SoftUni Team Technical Trainers
Application Architecture, Redux
ASP.NET Integration Testing
ASP.NET Unit Testing Unit Testing Web API SoftUni Team ASP.NET
Mocking tools for easier unit testing
Parsing JSON JSON.NET, LINQ-to-JSON
JavaScript Applications
State Management Cookies, Sessions SoftUni Team State Management
EF Code First (Advanced)
PHP MVC Frameworks MVC Fundamentals SoftUni Team Technical Trainers
OOP Course - Virtual Trip
Spring Filters Spring Interceptors SoftUni Team Spring Interceptors
Software Technologies
Entity Framework: Code First
Registration, Login, Thymeleaf
Data Definition and Data Types
Unit Testing with Mocha
Databases advanced Course Introduction SoftUni Team Databases advanced
Debugging and Troubleshooting Code
Entity Framework: Relations
Array and List Algorithms
Functional Programming
The Right Way Control Flow
ASP.NET Razor Engine SoftUni Team ASP.NET MVC Introduction
MVC Architecture, Symfony Framework for PHP Web Apps
Processing Variable-Length Sequences of Elements
AJAX and jQuery AJAX AJAX Concepts, XMLHttpRequest, jQuery AJAX: $.ajax(), $.get(), $.post() jQuery AJAX XMLHttpRequest SoftUni Team Technical Trainers.
ASP.NET MVC Introduction
JavaScript Fundamentals
Databases Advanced Course Introduction SoftUni Team Databases Advanced
C# Web Development Basics
Creating UI elements with Handlebars
Best practices and architecture
Error Handling and Exceptions
Arrays and Multidimensional Arrays
Multidimensional Arrays, Sets, Dictionaries
Extending functionality using Collections
Exporting and Importing Data
Making big SPA applications
ASP.NET Razor Engine SoftUni Team ASP.NET MVC Introduction
C# Advanced Course Introduction SoftUni Team C# Technical Trainers
Course Overview, Trainers, Evaluation
Exporting and Importing Data
Scheduled Tasks and Web Socket
CSS Transitions and Animations
Train the Trainers Course
Spring Data Advanced Querying
Directives & Forms Capturing User Input SoftUni Team
Version Control Systems
JavaScript Frameworks & AngularJS
Polymorphism, Interfaces, Abstract Classes
/^Hel{2}o\s*World\n$/
First-Class Functions
JavaScript: ExpressJS Overview
CSS Transitions and Animations
Iterators and Generators
Presentation transcript:

Helpers, Data Validation Advanced Thymeleaf Helpers, Data Validation Thymeleaf Engine SoftUni Team Technical Trainers Software University http://softuni.bg

Table of Contents Helpers Data Validation Dates Strings Numbers Aggregates Data Validation

Have a Question? sli.do #JavaWeb

What are Helpers?

Helpers Objects that provide built-in functionalities that helps you enhance your view Dates Strings List Thymeleaf Numbers

Date – Custom Format Format Date WhiskeyController.java @GetMapping("/home") public String getHomePage(Model model){ model.addAttribute("myDate", new Date()); return "whiskey-home"; } Format Date whiskey-home.html <div th:text="${#dates.format(myDate,'yyyy-MMM-dd')}"></div>

Date – Week Name of Day Day Name WhiskeyController.java @GetMapping("/home") public String getHomePage(Model model){ model.addAttribute("myDate", new Date()); return "whiskey-home"; } Day Name whiskey-home.html <div th:text="${#dates.dayOfWeekName(myDate)}"></div>

Date – List Days List Days WhiskeyController.java @GetMapping("/home") public String getHomePage(Model model){ model.addAttribute("myDates", myDates); //2016-12-12, 2017-04-09 -> yyyy-MM-dd return "whiskey-home"; } List Days whiskey-home.html <div th:text="${#dates.listDay(myDates)}"></div>

Date – Get Current Date Today’s Date WhiskeyController.java @GetMapping("/home") public String getHomePage() { return "whiskey-home"; } Today’s Date whiskey-home.html <div th:text="${#dates.createNow()}"></div>

Strings – Is Empty Null/Empty Check WhiskeyController.java @GetMapping("/home") public String getHomePage(Model model) { String whiskeyNull = null; model.addAttribute("whiskey", whiskeyNull); return "whiskey-home"; } Null/Empty Check whiskey-home.html <div th:text="${#strings.isEmpty(whiskey)}"></div>

Strings – Substring Substring WhiskeyController.java @GetMapping("/home") public String getHomePage(Model model) { String whiskey = "Jack Daniels"; model.addAttribute("whiskey", whiskey); return "whiskey-home"; } Substring whiskey-home.html <div th:text="${#strings.substring(whiskey,0,4)}"></div>

Strings – Join Join WhiskeyController.java @GetMapping("/home") public String getHomePage(Model model) { model.addAttribute("whiskeys", whiskeys); //Jack Daniels, Jameson return "whiskey-home"; } Join whiskey-home.html <div th:text="${#strings.listJoin(whiskeys,'-')}"></div>

Strings – Capitalize Capitalize WhiskeyController.java @GetMapping("/home") public String getHomePage(Model model) { String whiskey = “jameson"; model.addAttribute("whiskey", whiskey); return "whiskey-home"; } Capitalize whiskey-home.html <div th:text="${#strings.capitalize(whiskey)}"></div>

Numbers - Format Format WhiskeyController.java @GetMapping("/home") public String getHomePage(Model model) { double num = 3.14159; model.addAttribute("num", num); return "whiskey-home"; } Format whiskey-home.html <div th:text="${#numbers.formatDecimal(num,1,2)}"></div>

Numbers - Sequence Sequence WhiskeyController.java @GetMapping("/home") public String getHomePage(Model model) { return "whiskey-home"; } Sequence whiskey-home.html <span th:each="number: ${#numbers.sequence(0,2)}"> <span th:text="${number}"></span> </span>

Aggregates - Sum Sum WhiskeyController.java @GetMapping("/home") public String getHomePage(Model model) { double[] whiskeyPrices = new double[]{29.23, 21.22,33.50}; model.addAttribute("whiskeyPrices",whiskeyPrices); return "whiskey-home"; } Sum whiskey-home.html <div th:text="${#aggregates.sum(whiskeyPrices)}

Thymeleaf in JavaScript JSController.java @GetMapping("/js") public String getMapPage(Model model){ String message = "Hi JS!"; model.addAttribute("message", message); return "page"; } script.js <script th:inline="javascript"> var message = [[${message}]]; <script>

How to validate?

Spring Validation Model SomeModel.java public class SomeModel { @NotNull @Size(min = 3, max = 10, message = "Invalid name") private String name; } Not Null Error Message Size

Spring Validation Controller (1) SomeController.java @Controller public class SomeController { @GetMapping("/add") public String getPage(@ModelAttribute SomeModel someModel) { return "add"; } Sending a model to the view

Spring Validation Controller (1) Validate the model SomeController.java @PostMapping("/add") public String add (@Valid @ModelAttribute SomeModel someModel, BindingResult bindingResult) { if(bindingResult.hasErrors()){ return "add"; } this.someService.save(someModel); return "redirect:/home"; Validation Result

Spring Validation Thymeleaf add.html Get Object <form method="post" th:object="${someModel}"> <div class="form-group" th:classappend="${#fields.hasErrors('name')}? 'has-danger'"> <label for="nameId">Name</label> <input type="text" th:field="*{name}"/> <small id="nameHelp" th:each="error : ${#fields.errors('name')}" th:text="${error}“ Error Message </small> </div> </form> Append Class Access Field Print Error

List All Errors add.html <ul th:if="${#fields.hasErrors('*')}"> <li th:each="err : ${#fields.errors('*')}" th:text="${err}"> Input is incorrect </li> </ul>

List Errors Outside the Form add.html <ul th:if="${#fields.hasErrors('${someModel.*}')}"> <li th:each="err : ${#fields.errors('${someModel.*}')}" th:text="${err}"> Input is incorrect </li> </ul>

Custom Annotations (1) PresentOrFuture.java @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.FIELD) @Constraint(validatedBy = PresentOrFutureValidator.class) public @interface PresentOrFuture { String message() default "Invalid Date"; Class<?>[] groups() default {}; Class<? extends Payload>[] payload() default {}; }

True = No Error; False = Error Custom Annotations (2) add.html Annotation public class PresentOrFutureValidator implements ConstraintValidator<PresentOrFuture, Date> { @Override public boolean isValid(Date date, ConstraintValidatorContext constraintValidatorContext) { Date today = new Date(); return date.after(today); } Field Type True = No Error; False = Error

Summary Helpers – Additional Object that provide built-in functionalities for strings, numbers, arrays, errors etc. Data Validation – validate models by using: Validation Annotations – constraints(@Size, @NotNull etc) @Valid – Validates the model Binding Result – returns the validation errors #fields.errors – get the errors in Thymeleaf

Web Development Basics – Course Overview https://softuni.bg/courses/ © Software University Foundation – http://softuni.org This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.

License This course (slides, examples, demos, videos, homework, etc.) is licensed under the "Creative Commons Attribution- NonCommercial-ShareAlike 4.0 International" license © Software University Foundation – http://softuni.org This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.

Free Trainings @ Software University Software University Foundation – softuni.org Software University – High-Quality Education, Profession and Job for Software Developers softuni.bg Software University @ Facebook facebook.com/SoftwareUniversity Software University @ YouTube youtube.com/SoftwareUniversity Software University Forums – forum.softuni.bg © Software University Foundation – http://softuni.org This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.