Hackforge Academy

Category: java

spring boot and javascript form vaildation

Published on 02 Apr 2026

Explanation

Create a simple HTML login form with username and password input fields and a submit button.

Code:

<form id="loginForm" onSubmit="validate()">
  <input type="text" id="username" placeholder="Enter username" />
  <input type="password" id="password" placeholder="Enter password" />
  <button type="submit">Login</button>
</form>

<p id="error"></p>

Explanation

Add JavaScript validation to check whether username and password fields are empty before making the API request.

Code:

function validate(){
  const username = document.getElementById("username").value;
  const password = document.getElementById("password").value;
  if(username === "" || password === "") {
    document.getElementById("error").innerText = "All fields are required";
    return;
  }
  loginUser(username, password);
}

Explanation

Use fetch API to send login credentials to the backend REST API.

Code:

function loginUser(username, password) {
  fetch("http://localhost:8080/api/login", {
    method: "POST",
    headers: {
      "Content-Type": "application/json"
    },
    body: JSON.stringify({ username, 
password })
  })
  .then(res => res.json())
  .then(data => console.log(data));
}

Explanation

Create a Spring Boot REST controller to receive login request from frontend.

Code:

@RestController
@RequestMapping("/api")
public class LoginController {

  @PostMapping("/login")
  public String login(
@RequestBody LoginRequest request) {
    if(request.getUsername().equals("admin")
 && request.getPassword().equals("1234")) {
      return "Login successful";
    }

    return "Invalid credentials";
  }
}

Explanation

Create a LoginRequest model class to map username and password from request body.

Code:

public class LoginRequest {

  private String username;
  private String password;

  public String getUsername() {
    return username;
  }

  public void setUsername(String username) {
    this.username = username;
  }

  public String getPassword() {
    return password;
  }

  public void setPassword(String password) {
    this.password = password;
  }
}

πŸš€ Learn Spring Boot with real-world projects

πŸ’‘ Build REST APIs step by step

🧠 Improve backend development skills

🎯 Get career-ready practical training

Join Our Free WhatsApp Community

Direct access to niche-specific mentors and peers on WhatsApp.

🐍

Python Community

Discuss Django, FastAPI, AI integration, and automation scripts with 15k+ developers.

Join Python Community
βš›οΈ

React Community

Master Next.js, Framer Motion, and State Management. Share your latest UI components.

Join React Community
β˜•

Java Community

Deep dives into Spring Boot, Microservices architecture, and high-performance backend ops.

Join Java Community