MSK Institute LogoMSK.Institute
HomeCourses
Book Free Demo➔Sign In
Free Demo➔
MSK Institute LogoMSK.Institute

Leading computer training academy in Shikohabad for software engineering, Python, web development, and digital literacy.

ISO 9001:2015 Certified Center
Follow & Connect
4.9

Programs & Admissions

  • All CoursesCatalog
  • Learning PathsRoadmaps
  • Student ProjectsShowcase
  • Live Classes & ScheduleLive
  • Upcoming Batches
  • Campuses & LocationsHub
  • Verify Certificates
  • Book Free Demo Class

Resources & Tools

  • Free Online Mock TestsAll Tests
  • NIELIT CCC Mock TestFree
  • Course & Career FinderQuiz
  • Study Material Hub
  • All MSK ToolsHub
  • Keyboard ShortcutsNew
  • TypeQuest Speed LabTyping
  • MSK Code PlaygroundCode
  • Interactive Tutorials
  • Quick Cheatsheets

Institute & Contact

  • About MSK Institute
  • Careers & InternshipsHiring
  • Publications & Blogs
  • Gali No. 3, Near Gyan Jyoti Public School,
    Adarsh Nagar, Shikohabad, Uttar Pradesh 283135
  • +91 83930 42166
  • mskshikohabad@gmail.com
  • Hours:Mon – Sat: 8:00 AM – 7:00 PM | Sun: 10:00 AM – 2:00 PM
  • 4.9 ★(38 Google Reviews)
© 2026 MSK Institute. All rights reserved.•Privacy Policy•Terms of Service•Disclaimer•Contact Us

Shikohabad's Leading Computer & Coding Academy

Home
Courses
Live
Material
Form Events and Validation0%
Study Materials
JavaScript for IntermediateProgress 0%
1.1Block Scope with let & const1.2Template Literals1.3Destructuring Arrays and Objects1.4Default Parameters1.5Enhanced Object Literals
4.1Event Listeners4.2Event Bubbling & Capturing4.3Keyboard & Mouse Events4.4Form Events and Validation
HomeTutorialsJavaScript for IntermediateForm Events and Validation
map, filter, reduce

Form Events and Validation

Beginner12 min read•Updated: 2026-09-15•By Er. Sumit Kumar (MSK Institute)
Study Materials

Form Events & Validation in Modern JavaScript

Forms are the primary mechanism through which web applications collect user data. Robust client-side validation, smooth input feedback, and secure form submission handling are critical for delivering seamless user experiences and clean data payloads.


1. Essential Form Events

EventFires When...Typical Use Case
submitThe form is submitted (Enter pressed or submit button clicked)Intercepting page reload, full validation, API dispatch
inputThe value of an <input>, <textarea>, or <select> changes immediatelyReal-time validation, character counters, live preview
changeThe element loses focus after value has changed (or checkbox toggled)Committing selections, debounced validations
focusAn element gains focus (Does not bubble)Highlighting input active states, showing helper tooltips
blurAn element loses focus (Does not bubble)Field-level validation once user leaves input
1const emailInput = document.querySelector('#email-field');
2 
3// Immediate feedback as user types
4emailInput.addEventListener('input', (e) => {
5 console.log('Current value:', e.target.value);
6});
7 
8// Validation on leaving field
9emailInput.addEventListener('blur', (e) => {
10 validateEmail(e.target.value);
11});

2. Preventing Form Submission with preventDefault()

By default, an HTML <form> triggers an HTTP POST/GET request that refreshes the page. In modern SPA architectures, intercept this with e.preventDefault():

1const registrationForm = document.querySelector('#form-register');
2 
3registrationForm.addEventListener('submit', async (event) => {
4 event.preventDefault(); // Stop default browser page reload!
5 
6 // Perform form validation
7 if (!validateForm()) {
8 return;
9 }
10 
11 // Extract form data and send via fetch
12 const formData = new FormData(registrationForm);
13 const payload = Object.fromEntries(formData.entries());
14 
15 console.log('Sending payload to server:', payload);
16});

3. Extracting Form Data: The FormData API

The modern FormData API extracts all named form fields automatically:

1<form id="profile-form">
2 <input type="text" name="username" value="alex_dev" />
3 <input type="email" name="email" value="alex@example.com" />
4 <select name="role">
5 <option value="developer" selected>Developer</option>
6 <option value="manager">Manager</option>
7 </select>
8</form>

4. Constraint Validation API

Modern browsers include built-in validation attributes: required, type="email", minlength="8", pattern="[A-Za-z]+". JavaScript can interact directly with this engine via the Constraint Validation API:

1const passwordInput = document.querySelector('#password');
2 
3// Checking validity
4if (!passwordInput.checkValidity()) {
5 console.log('Error reason:', passwordInput.validationMessage);
6 console.log('Validity State:', {
7 valueMissing: passwordInput.validity.valueMissing,
8 tooShort: passwordInput.validity.tooShort,
9 patternMismatch: passwordInput.validity.patternMismatch
10 });
11}
12 
13// Custom error message
14if (passwordInput.value.length < 8) {
15 passwordInput.setCustomValidity('Password must contain at least 8 characters!');
16} else {
17 passwordInput.setCustomValidity(''); // Empty string resets validity to valid!
18}

5. Complete Field Validation Pattern

1function setupRealtimeValidation() {
2 const form = document.querySelector('#signup-form');
3 const email = form.querySelector('#email');
4 const errorContainer = form.querySelector('#email-error');
5 
6 function validateEmailField() {
7 const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
8 const value = email.value.trim();
9 
10 if (!value) {
11 errorContainer.textContent = 'Email address is required.';
12 email.classList.add('invalid');
13 return false;
14 } else if (!emailRegex.test(value)) {
15 errorContainer.textContent = 'Please enter a valid email address.';
16 email.classList.add('invalid');
17 return false;
18 } else {
19 errorContainer.textContent = '';
20 email.classList.remove('invalid');
21 email.classList.add('valid');
22 return true;
23 }
24 }
25 
26 email.addEventListener('input', validateEmailField);
27 email.addEventListener('blur', validateEmailField);
28 
29 form.addEventListener('submit', (e) => {
30 e.preventDefault();
31 if (validateEmailField()) {
32 console.log('Form validated successfully. Submitting...');
33 }
34 });
35}

Interactive Quiz• Knowledge Check

Practice Quiz

Question 1
Which event fires immediately every time the text value of an <input> is altered by a keystroke?
Question 2
Why is event.preventDefault() called in a form submit event handler?
Question 3
What is the most convenient way to convert an entire HTML form's named inputs into a standard JavaScript object?
Question 4
In the Constraint Validation API, how do you clear a custom validation error previously set via setCustomValidity()?
Question 5
Which event fires when an input loses focus after its value has been modified?
Next Lesson

map, filter, reduce

Continue learning with hands-on practice, examples, and exercises in the upcoming topic.

Related Lessons

Previous LessonNext Lesson
Keyboard & Mouse Eventsmap, filter, reduce

Practice Quiz

Test your understanding of this lesson with 5 questions. Each question has one correct answer.

Mentor-Led Practical Training

Master JavaScript for Intermediate with Hands-On Projects

Practice in live mentor-led sessions with real projects, mock tests, and verifiable certification at MSK Institute.

View Full CourseBook Free Demo
PreviousNext
PreviousPrevNext