In today's digital world, whenever we fill an online form, the first expectation is that the user fills in the correct information. But if someone fills even one letter wrong by mistake, the entire process can be spoiled. In such a situation, JavaScript form validation becomes very important.
| JavaScript Name Validation Form - HTML, CSS and JS |
In this article we will understand how to do Name Validation through JavaScript. We will understand a beautiful and responsive project which is built with the help of HTML, CSS, and JavaScript.
You will find a source code in this article, in which we have created validation to check the correct format of the name. This article is technically strong, but the language is kept so simple that even a beginner can understand it well.
What is JavaScript Validation?
JavaScript Validation means that when a user enters something in an input field of the website (such as name, email, password), JavaScript immediately checks the entered data and tells whether it is correct or not.
Name validation is necessary so that the user does not enter any wrong or incomplete name, such as just one letter or number.
Some benefits of JavaScript Name Validation Project
In the points given below, we will see some main benefits of this project:
- This project is responsive and user-friendly, that is, it runs well on both mobile and computer.
- Its design is modern and attractive, which gives the user an interactive experience.
- Real-time validation is given – that is, as soon as the user types, the validation appears immediately.
- If the user enters something wrong, the error message appears clearly in the form of an alert.
- Success message also comes in the alert box which makes the form more professional.
- The code is completely modular – HTML, CSS and JavaScript are kept separate.
- Any beginner can easily understand this source code and use it in his project.
Source Code of HTML and its easy Explanation
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Enhanced Name Validation</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-QWTKZyjpPEjISv5WaRU9OFeRpok6YctnYmDr5pNlyT2bRjXh0JMhjY6hW+ALEwIH" crossorigin="anonymous">
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="particles"></div>
<div class="container mt-5">
<div class="row">
<div class="col-lg-12">
<div class="card">
<div class="card-header wrapper">
<h3 class="title">Rays Coding :- JavaScript Validation</h3>
</div>
<div class="card-body">
<form action="" method="post">
<div class="row">
<div class="col-lg-12">
<div class="mb-3 field">
<input type="text" class="form-control" id="name" name="username" autocomplete="off">
<i class="fas fa-user input-icon"></i>
<label for="name" class="form-label">Name</label>
<i class="fas fa-check-circle validation-icon success"></i>
<i class="fas fa-exclamation-circle validation-icon error"></i>
</div>
</div>
</div>
<div class="row error-row" id="errorRow" style="display: none;">
<div class="col-lg-12">
<div class="mb-3 field">
<div class="alert alert-danger" id="error"></div>
</div>
</div>
</div>
<div class="row success-row" id="successRow" style="display: none;">
<div class="col-lg-12">
<div class="mb-3 field">
<div class="alert alert-success" id="success"></div>
</div>
</div>
</div>
<div class="row">
<div class="col-lg-12">
<div class="field">
<button type="button" class="btn btn-primary w-100" onclick="validation()">
<span id="btnText">SUBMIT</span>
</button>
</div>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
<script src="script.js"></script>
</body>
</html>
The HTML part of this project forms the structure of the website. It has a form with a name field. This field comes inside a beautiful card, which makes the website look professional.
Bootstrap has been used in this, which creates a mobile-friendly layout. With the help of Font Awesome, we show icons (such as user icon, success and error icon) in the input field.
In HTML, we have created three main message boxes:
- Error Row: When the name is empty or wrong.
- Success Row: When the name is correct and the form is submitted.
- Submit Button: When clicked, validation runs.
The entire layout is created using input, label, and div tags in the HTML structure. There is no database or backend work in this, all the work is done on the frontend through JavaScript.
You can easily use this HTML source code in your blog or website.
CSS Source Code and its Easy Explanation
@import url('https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap');
* {
margin: 0;
padding: 0;
box-sizing: border-box;
font-family: 'Inter', sans-serif;
}
body {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
height: 100vh;
position: relative;
overflow: hidden;
display: flex;
align-items: center;
justify-content: center;
}
/* Animated background particles */
.particles {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
pointer-events: none;
z-index: 1;
}
.particle {
position: absolute;
width: 3px;
height: 3px;
background: rgba(255, 255, 255, 0.4);
border-radius: 50%;
animation: float 8s ease-in-out infinite;
}
@keyframes float {
0%,
100% {
transform: translateY(0px) rotate(0deg);
opacity: 0.4;
}
50% {
transform: translateY(-80px) rotate(180deg);
opacity: 0.8;
}
}
.container {
position: relative;
z-index: 2;
padding: 0;
margin: 0;
width: 100%;
max-width: 500px;
}
.card {
width: 100%;
max-width: 500px;
margin: 0 20px;
border: none;
box-shadow:
0 25px 50px rgba(0, 0, 0, 0.2),
0 0 0 1px rgba(255, 255, 255, 0.1);
border-radius: 24px;
backdrop-filter: blur(20px);
background: rgba(255, 255, 255, 0.95);
overflow: hidden;
animation: slideUp 0.8s cubic-bezier(0.25, 0.46, 0.45, 0.94);
}
@keyframes slideUp {
from {
opacity: 0;
transform: translateY(50px);
}
to {
opacity: 1;
transform: translateY(0);
}
}
.wrapper {
background: linear-gradient(135deg, #667eea, #764ba2);
padding: 30px 5px;
position: relative;
overflow: hidden;
}
.wrapper::before {
content: '';
position: absolute;
top: -50%;
left: -50%;
width: 200%;
height: 200%;
background: radial-gradient(circle, rgba(255, 255, 255, 0.1) 0%, transparent 70%);
animation: rotate 20s linear infinite;
}
@keyframes rotate {
0% {
transform: rotate(0deg);
}
100% {
transform: rotate(360deg);
}
}
.title {
color: #fff;
text-shadow: 0 2px 10px rgba(0, 0, 0, 0.3);
text-align: center;
font-weight: 700;
font-size: 28px;
position: relative;
z-index: 1;
}
.card-body {
padding: 40px;
background: rgba(255, 255, 255, 0.98);
}
.field {
margin-top: 30px;
position: relative;
}
.field input.form-control {
height: 60px;
width: 100%;
font-size: 18px;
padding: 0 20px 0 55px;
border: 2px solid #e1e5e9;
border-radius: 16px;
transition: all 0.3s cubic-bezier(0.25, 0.46, 0.45, 0.94);
background: rgba(255, 255, 255, 0.9);
backdrop-filter: blur(10px);
font-weight: 400;
}
.field input.form-control:focus {
border-color: #667eea;
box-shadow: 0 0 0 4px rgba(102, 126, 234, 0.15);
outline: none;
transform: translateY(-2px);
background: rgba(255, 255, 255, 1);
}
.field input.form-control:valid {
border-color: #10b981;
}
.input-icon {
position: absolute;
left: 18px;
top: 50%;
transform: translateY(-50%);
font-size: 20px;
color: #9ca3af;
transition: all 0.3s ease;
z-index: 10;
}
.field input.form-control:focus+.input-icon {
color: #667eea;
transform: translateY(-50%) scale(1.1);
}
.field input.form-control:valid+.input-icon {
color: #10b981;
}
.field label {
position: absolute;
top: 50%;
left: 55px;
color: #9ca3af;
font-size: 16px;
font-weight: 400;
pointer-events: none;
transform: translateY(-50%);
transition: all 0.3s cubic-bezier(0.25, 0.46, 0.45, 0.94);
background: rgba(255, 255, 255, 0.9);
padding: 0 8px;
z-index: 5;
}
.field input.form-control:focus~label,
.field input.form-control:valid~label {
top: 0;
font-size: 13px;
font-weight: 600;
color: #667eea;
transform: translateY(-50%);
left: 50px;
background: rgba(255, 255, 255, 1);
}
.validation-icon {
position: absolute;
right: 20px;
top: 50%;
transform: translateY(-50%);
font-size: 18px;
opacity: 0;
transition: all 0.3s ease;
z-index: 10;
}
.validation-icon.show {
opacity: 1;
transform: translateY(-50%) scale(1);
}
.validation-icon.success {
color: #10b981;
}
.validation-icon.error {
color: #ef4444;
}
.field button {
height: 60px;
border: none;
border-radius: 16px;
background: linear-gradient(135deg, #667eea, #764ba2);
color: #fff;
font-size: 18px;
font-weight: 600;
transition: all 0.3s cubic-bezier(0.25, 0.46, 0.45, 0.94);
position: relative;
overflow: hidden;
cursor: pointer;
}
.field button::before {
content: '';
position: absolute;
top: 50%;
left: 50%;
width: 0;
height: 0;
background: rgba(255, 255, 255, 0.2);
border-radius: 50%;
transition: all 0.4s ease;
transform: translate(-50%, -50%);
}
.field button:hover::before {
width: 300px;
height: 300px;
}
.field button:hover {
background: linear-gradient(135deg, #556cd6, #6d4294);
transform: translateY(-3px);
box-shadow: 0 20px 40px rgba(102, 126, 234, 0.4);
}
.field button:active {
transform: translateY(-1px);
}
.field button span {
position: relative;
z-index: 1;
}
.alert {
margin-top: 20px;
border-radius: 12px;
padding: 16px 20px;
font-weight: 500;
border: none;
animation: slideIn 0.4s cubic-bezier(0.25, 0.46, 0.45, 0.94);
}
@keyframes slideIn {
from {
opacity: 0;
transform: translateY(-15px);
}
to {
opacity: 1;
transform: translateY(0);
}
}
.alert-danger {
background: linear-gradient(135deg, #fef2f2, #fee2e2);
color: #dc2626;
border-left: 4px solid #dc2626;
}
.alert-success {
background: linear-gradient(135deg, #f0fdf4, #dcfce7);
color: #16a34a;
border-left: 4px solid #16a34a;
}
@media screen and (max-width: 768px) {
.card {
width: calc(100% - 40px);
margin: 0 20px;
}
.card-body {
padding: 25px 20px;
}
.title {
font-size: 22px;
}
.field input.form-control {
height: 55px;
font-size: 16px;
}
.field button {
height: 55px;
font-size: 16px;
}
}
/* Loading animation */
.loading {
display: inline-block;
width: 20px;
height: 20px;
border: 2px solid rgba(255, 255, 255, 0.3);
border-radius: 50%;
border-top-color: white;
animation: spin 0.8s linear infinite;
}
@keyframes spin {
to {
transform: rotate(360deg);
}
}
CSS has been used in this project not only for design but also to make the user interaction visually good.
Many things have been done with the help of CSS in this source code:
- The entire background is filled with a beautiful gradient which gives a modern look to the page.
- The card has been given a very clean and minimal look with shadow and blur.
- Animation, focus effect and icons have been used to make the input field stylish.
- When the input is correct, a green border appears (success), and if it is wrong, a red border appears (error).
- Validation icons like ✔️ and ❌ are also shown accordingly.
- The Submit button has a ripple effect and hover animations which make the button very attractive.
- Alerts (error or success messages) are shown with a smooth slide-in animation.
- Media queries have also been added to CSS keeping in mind responsive design.
Apart from this, a class named .particle has been created for animated background particles, which makes small dots move up and down and makes the whole page lively.
This CSS source code is completely modular and you can easily add it to any of your projects.
Now let's talk about the most important part - the JavaScript code.
This script has three main functionalities:
// Create animated particles
function createParticles() {
const particles = document.querySelector('.particles');
const particleCount = 30;
for (let i = 0; i < particleCount; i++) {
const particle = document.createElement('div');
particle.className = 'particle';
particle.style.left = Math.random() * 100 + '%';
particle.style.top = Math.random() * 100 + '%';
particle.style.animationDelay = Math.random() * 8 + 's';
particle.style.animationDuration = (Math.random() * 4 + 4) + 's';
particles.appendChild(particle);
}
}
// Initialize particles
createParticles();
const nameInput = document.getElementById('name');
const errorRow = document.getElementById('errorRow');
const successRow = document.getElementById('successRow');
const errorDiv = document.getElementById('error');
const successDiv = document.getElementById('success');
const btnText = document.getElementById('btnText');
const submitBtn = document.querySelector('button[onclick="validation()"]');
// Real-time validation with visual feedback
nameInput.addEventListener('input', function () {
const value = this.value.trim();
const successIcon = document.querySelector('.validation-icon.success');
const errorIcon = document.querySelector('.validation-icon.error');
if (value.length === 0) {
this.style.borderColor = '#e1e5e9';
successIcon.classList.remove('show');
errorIcon.classList.remove('show');
} else if (value.length >= 2 && /^[a-zA-Z\s]+$/.test(value)) {
this.style.borderColor = '#10b981';
successIcon.classList.add('show');
errorIcon.classList.remove('show');
} else {
this.style.borderColor = '#ef4444';
errorIcon.classList.add('show');
successIcon.classList.remove('show');
}
});
function validation() {
const name = nameInput.value.trim();
// Hide previous alerts
errorRow.style.display = 'none';
successRow.style.display = 'none';
// Show loading
btnText.innerHTML = '<div class="loading"></div>';
submitBtn.disabled = true;
setTimeout(() => {
if (name === '') {
errorDiv.textContent = 'Name field cannot be empty!';
errorRow.style.display = 'block';
} else if (name.length < 2) {
errorDiv.textContent = 'Name must be at least 2 characters long!';
errorRow.style.display = 'block';
} else if (!/^[a-zA-Z\s]+$/.test(name)) {
errorDiv.textContent = 'Name should contain only letters and spaces!';
errorRow.style.display = 'block';
} else {
successDiv.textContent = `Hello ${name}! Form submitted successfully.`;
successRow.style.display = 'block';
// Reset form after 3 seconds
setTimeout(() => {
nameInput.value = '';
nameInput.style.borderColor = '#e1e5e9';
document.querySelectorAll('.validation-icon').forEach(icon => {
icon.classList.remove('show');
});
successRow.style.display = 'none';
}, 3000);
}
// Reset button
btnText.textContent = 'SUBMIT';
submitBtn.disabled = false;
}, 1500);
}
// Enter key submission
nameInput.addEventListener('keypress', function (e) {
if (e.key === 'Enter') {
validation();
}
});
1. Animated Background Particles
The first task of JavaScript is to create 30 small white dots on the page that move randomly. These particles are created in a div named .particles. A div is created for each particle and it is positioned at a random place.
This whole animation gives a premium and animated feel to the website.
2. Real-Time Name Validation
The second function of JavaScript is to validate the name. As the user types something in the input box:
- If the name is blank, the border is gray and no icon is displayed.
- If the name is less than 2 characters, or contains numbers/symbols, an error icon and red border are displayed.
- If the name is 2 or more characters and contains only alphabets, a green border and success icon are displayed.
This feature gives immediate feedback to the user, so that they do not make mistakes while filling the form.
3. Validation Logic of Submit Button
When the SUBMIT button is clicked:
- First the previous error or success messages are hidden.
- Then a loading animation appears on the button (a rotating animation).
- JavaScript checks after 1.5 seconds:
- If the name is empty, an error message is displayed in the alert – “Name field cannot be empty!”
- If the name is less than 2 characters, an error alert appears.
- If the name contains any special character or number, an error alert appears.
- If everything is correct, a success message is displayed – “Hello [name]! Form submitted successfully.”
After this, the form is reset after 3 seconds – i.e. the input field becomes empty again and the icons disappear.
There is another feature with this – if the user presses the Enter key, the same validation will run again.
This entire JavaScript source code is well designed and modular, and is ideal for beginners.
Conclusion – The real source of learning
In this article, we learned how to create a simple but attractive JavaScript Name Validation project. In this, we understood HTML, CSS, and JavaScript in all three parts.
Such projects are a great source for beginners to improve their coding skills.
You can integrate this source code into your blog, portfolio, or any web application.
Validation not only prevents user mistakes but also makes your website professional.