0% found this document useful (0 votes)
1 views15 pages

Lecture JS - Javascript APIs - Part 4

The document discusses form validation in JavaScript, emphasizing its importance for user experience, security, and efficiency. It provides examples of basic validation techniques, including checking required fields, validating email formats, and ensuring password strength, along with real-time validation and using external libraries. Best practices include validating on both client and server sides, providing real-time feedback, and maintaining a user-friendly experience.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views15 pages

Lecture JS - Javascript APIs - Part 4

The document discusses form validation in JavaScript, emphasizing its importance for user experience, security, and efficiency. It provides examples of basic validation techniques, including checking required fields, validating email formats, and ensuring password strength, along with real-time validation and using external libraries. Best practices include validating on both client and server sides, providing real-time feedback, and maintaining a user-friendly experience.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 15

Form Validation in JavaScript

What is Form Validation?


Definition: Ensures that user input meets specific criteria before submitting a form.
Purpose:
 Prevent bad data submission.
Improve user experience.
Reduce server load by filtering invalid data early.
Why Validate Forms?
User Experience: Provides immediate feedback to users on incorrect input.
Security: Reduces the risk of malformed data reaching the server.
Efficiency: Saves server resources by rejecting invalid input.
Basic JavaScript Validation
<form id="myForm">
<input type="text" id="name" name="name" required>
<input type="email" id="email" name="email" required>
<button type="submit">Submit</button>
</form>

<script>
document.getElementById('myForm').addEventListener('submit', function(e) {
let name = document.getElementById('name').value;
if (name === '') {
alert("Name is required!");
e.preventDefault();
}
});
</script>
Validating Text Inputs
<form id="myForm">
<label for="name">Name (min 3 characters):</label>
<input type="text" id="name" name="name" required>
<button type="submit">Submit</button>
</form>

<script>
document.getElementById('myForm').addEventListener('submit', function(e) {
let name = document.getElementById('name').value;
if (name.length < 3) {
alert("Name must be at least 3 characters.");
e.preventDefault();
}
});
</script>
Validating Email Format
<form id="myForm">
<label for="email">Email:</label>
<input type="email" id="email" name="email" required>
<button type="submit">Submit</button>
</form>

<script>
document.getElementById('myForm').addEventListener('submit', function(e) {
let email = document.getElementById('email').value;
const emailPattern = /^[^ ]+@[^ ]+\.[a-z]{2,3}$/;
if (!emailPattern.test(email)) {
alert("Invalid email address");
e.preventDefault();
}
});
</script>
Password Validation
<form id="myForm">
<label for="password">Password (at least 8 characters, 1 uppercase, 1 number):</label>
<input type="password" id="password" name="password" required>
<button type="submit">Submit</button>
</form>

<script>
document.getElementById('myForm').addEventListener('submit', function(e) {
let password = document.getElementById('password').value;
const pwdPattern = /^(?=.*[A-Z])(?=.*\d).{8,}$/;
if (!pwdPattern.test(password)) {
alert("Password must be at least 8 characters long, contain a number, and an uppercase letter.");
e.preventDefault();
}
});
</script>
Checkbox and Radio Validation
<form id="myForm">
<label><input type="radio" name="gender" value="male"> Male</label>
<label><input type="radio" name="gender" value="female"> Female</label>
<button type="submit">Submit</button>
</form>

<script>
document.getElementById('myForm').addEventListener('submit', function(e) {
if (!document.querySelector('input[name="gender"]:checked')) {
alert("Please select a gender.");
e.preventDefault();
}
});
</script>
Select Dropdown Validation
<form id="myForm">
<label for="country">Select Country:</label>
<select id="country" name="country" required>
<option value="">Select a country</option>
<option value="US">United States</option>
<option value="CA">Canada</option>
</select>
<button type="submit">Submit</button>
</form>
<script>
document.getElementById('myForm').addEventListener('submit', function(e) {
let country = document.getElementById('country').value;
if (country === "") {
alert("Please select a country.");
e.preventDefault();
}
});
</script>
File Input Validation
<form id="myForm">
<label for="fileInput">Upload Resume (max 2MB):</label>
<input type="file" id="fileInput" name="fileInput" required>
<button type="submit">Submit</button>
</form>

<script>
document.getElementById('myForm').addEventListener('submit', function(e) {
let file = document.getElementById('fileInput').files[0];
if (file && file.size > 2 * 1024 * 1024) { // 2MB
alert("File must be under 2MB.");
e.preventDefault();
}
});
</script>
Real-time Validation
<form id="myForm">
<label for="email">Email:</label>
<input type="email" id="email" name="email" required>
<button type="submit">Submit</button>
</form>

<script>
document.getElementById('email').addEventListener('input', function() {
let email = this.value;
const emailPattern = /^[^ ]+@[^ ]+\.[a-z]{2,3}$/;
if (!emailPattern.test(email)) {
this.setCustomValidity("Invalid email format");
} else {
this.setCustomValidity("");
}
});
</script>
Disable Submit Until Valid
<form id="myForm">
<input type="text" id="name" name="name" required>
<button type="submit" id="submitBtn" disabled>Submit</button>
</form>

<script>
const form = document.getElementById("myForm");
const submitBtn = document.getElementById("submitBtn");

form.addEventListener("input", function() {
submitBtn.disabled = !form.checkValidity(); // Disable button if form is invalid
});
</script>
Using Constraint Validation API
<form id="myForm">
<input type="text" id="name" name="name" required>
<button type="submit">Submit</button>
</form>

<script>
const form = document.getElementById('myForm');

form.addEventListener('submit', function(e) {
if (!form.reportValidity()) {
e.preventDefault(); // Prevent form submission if validation fails
}
});
</script>
External Libraries (Optional)
Parsley.js: A feature-rich, customizable form validation library.
Validate.js: A lightweight library for simple validation.
jQuery Validation: Offers extensive form validation and error handling.
Always validate on both client and server for security and reliability.
Provide real-time feedback to users.
Avoid intrusive alerts; use inline messages.
Keep the UX in mind; be informative but concise.

You might also like