Hi everyone! Welcome to my another JavaScript series. Today I am going to write about how I create a login page validation using HTML, CSS, JavaScript. Let's see my step by step process.
Create the inputs (HTML) — add id
s so JS can find them.
<input id="userName" placeholder="Enter your Username">
<input id="passWord" type="password" placeholder="Enter your password">
<button id="loginBtn">Log In</button>
Why: id lets JavaScript get the element. type="password" hides the characters.
Add demo credentials (JS) — only for learning/demo.
let defaultUser = "sevaki";
let defaultPass = "1234";
Why: these are the values you compare against while practicing (not secure in real apps).
Write a login function — this runs when the user clicks Log In.
function login() {
// code goes here
}
Why: enclosing logic in a function means it runs only on demand (not at page load).
Read the current input values inside the function
let user = document.getElementById("userName").value;
let pass = document.getElementById("passWord").value;
Why: reading .value
inside the function gets what the user typed right now.
**
Compare the values** — check both username and password.
if (user === defaultUser && pass === defaultPass) { /* success */ }
else { /* failure */ }
Why: ===
checks exact match; use &&
to require both fields to match.
Show feedback — quick demo uses alert(), but inline messages are better UX.
alert("Login successfully"); // or alert("Login failed! Try again.")
Tip: later replace alert()
with updating a <p id="msg"></p>
for nicer UI.
Hook the function to the button
- Simple (beginner): add onclick="login()" to the button.
- Cleaner: attach in JS:
document.getElementById("loginBtn").addEventListener("click", login);
Why: this makes the button run the login code.
Test common cases
- Correct username/password → success.
- Wrong username or wrong password → failure.
- Empty fields → decide to show a “Please fill in” message. Tip: use user = user.trim() to ignore accidental spaces.
SO that's guys. Here I gave a brief explanation for step by step process. I hope I gave a clear and understandable steps. See you in my next blog.
Output: https://front-end-04f891.gitlab.io/loginpageValidation.html
source code: https://gitlab.com/cloning-projects/front-end/-/blob/main/loginpageValidation.html?ref_type=heads
Reference: https://www.geeksforgeeks.org/javascript/form-validation-using-javascript/
Top comments (1)
Validation learned! 🎓