Spring MVC and JQuery Ajax form submit and validation

Tools and technologies used:

  • Spring boot 2
  • JQuery
  • Gradle
  • IntelliJ IDEA

Project Structure

Spring MVC and JQuery Ajax form submit and validation project structure

Gradle dependency

1
implementation 'org.springframework.boot:spring-boot-starter-web'

Student.java

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
package com.shahediqbal.springajaxformvalidation.model;
 
import javax.validation.constraints.Email;
import javax.validation.constraints.NotEmpty;
 
public class Student {
    @NotEmpty(message = "Please enter first name.")
    private String firstName;
    @NotEmpty(message = "Please enter last name.")
    private String lastName;
    @NotEmpty(message = "Please enter email address.")
    @Email(message = "Please enter a valid email address.")
    private String email;
 
    public String getFirstName() {
        return firstName;
    }
 
    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }
 
    public String getLastName() {
        return lastName;
    }
 
    public void setLastName(String lastName) {
        this.lastName = lastName;
    }
 
    public String getEmail() {
        return email;
    }
 
    public void setEmail(String email) {
        this.email = email;
    }
}

StudentController.java

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
package com.shahediqbal.springajaxformvalidation.controller;
 
import com.shahediqbal.springajaxformvalidation.model.Student;
import com.shahediqbal.springajaxformvalidation.response.StudentResponse;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
 
import javax.validation.Valid;
import java.util.Map;
import java.util.stream.Collectors;
 
@Controller
public class StudentController {
 
    @PostMapping(value = "/saveStudent", produces = {MediaType.APPLICATION_JSON_VALUE})
    @ResponseBody
    public StudentResponse saveEmployee(@ModelAttribute @Valid Student student,
                                        BindingResult result) {
 
        StudentResponse response = new StudentResponse();
 
        if (result.hasErrors()) {
 
            Map<String, String> errors = result.getFieldErrors().stream()
                    .collect(
                            Collectors.toMap(FieldError::getField, FieldError::getDefaultMessage)
                    );
 
            response.setValidated(false);
            response.setErrorMessages(errors);
        } else {
 
            response.setValidated(true);
        }
        return response;
    }
}

StudentResponse.java

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
package com.shahediqbal.springajaxformvalidation.response;
 
import java.util.Map;
 
public class StudentResponse {
    private boolean validated;
    private Map<String, String> errorMessages;
 
    public boolean isValidated() {
        return validated;
    }
 
    public void setValidated(boolean validated) {
        this.validated = validated;
    }
 
    public void setErrorMessages(Map<String, String> errorMessages) {
        this.errorMessages = errorMessages;
    }
 
    public Map<String, String> getErrorMessages() {
        return errorMessages;
    }
}

index.html

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
<!DOCTYPE html>
<html>
<head>
    <script src="js/registration.js"></script>
</head>
<body>
 
<h2>Registration</h2>
 
<form id="registrationForm" action="/saveStudent">
    First name:<br>
    <input type="text" name="firstName" value="">
    <br>
    Last name:<br>
    <input type="text" name="lastName" value="">
    <br>
    email:<br>
    <input type="email" name="email" value="">
    <br><br>
    <input id="submitButton" type="submit" value="Submit">
</form>
 
</body>
</html>

registration.js

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
$(function () {
    $('#submitButton').click(function (e) {
 
        //Prevent default submission of form
        e.preventDefault();
 
        //Remove previous errors
        $('input').next('span').remove();
 
        $.post({
            url: '/saveStudent',
            data: $('#registrationForm').serialize(),
            success: function (res) {
                if (res.validated) {
                    //take your successful action here; you may want to redirect to another page
                    alert("Registration Successful");
                } else {
                    $.each(res.errorMessages, function (key, value) {
                        $('input[name=' + key + ']').after('<span class="error">' + value + '</span>');
                    });
                }
            }
        })
    });
 
});

Click for the full source code

Leave a Reply

Close Menu
Close Menu