Corporate Training
Request Demo
Click me
Menu
Let's Talk
Request Demo

Tutorials

Forms and Form Validation

Forms and Form Validation 

Forms play a crucial role in web development for collecting user input and sending it to a server. Form validation ensures that the data submitted by users meets the required criteria. Here's an introduction to forms and form validation in JavaScript:

Creating a Form:

In HTML, you create a form using the <form> element. Inside the form, you add various input elements like text fields, checkboxes, radio buttons, etc.

<form>
  <label for="username">Username:</label>
  <input type="text" id="username" name="username" required><br>
  
  <label for="password">Password:</label>
  <input type="password" id="password" name="password" required><br>
  
  <input type="submit" value="Submit">
</form>

       
 

Form Submission:

When a user clicks the submit button, the form's data is typically sent to a server for processing. You can intercept this process using JavaScript to perform client-side validation.

document.querySelector('form').addEventListener('submit', function(event) {
  event.preventDefault(); // Prevents the form from being submitted

  // Custom validation code can go here
});
 

Form Validation:

Form validation ensures that the data entered by the user is correct before it is submitted. You can use HTML attributes like required, pattern, and minlength to enforce certain rules. JavaScript can be used for more complex validations.

<input type="email" id="email" name="email" required>
<input type="number" id="age" name="age" min="18" required>
<input type="password" id="password" name="password" pattern=".{8,}" required>

       

 

Custom Validation with JavaScript:

You can use JavaScript to perform more advanced validation, such as checking if the password contains a mix of uppercase, lowercase, and special characters.

document.querySelector('form').addEventListener('submit', function(event) {
  event.preventDefault();

  let password = document.getElementById('password').value;

  if (!/[A-Z]/.test(password) || !/[a-z]/.test(password) || !/[^A-Za-z0-9]/.test(password)) {
    alert('Password must contain at least one uppercase letter, one lowercase letter, and one special character.');
    return;
  }

  // If the validation passes, you can proceed with form submission
});
 

Accessing Form Data:

You can use JavaScript to access the data entered by the user:

let username = document.getElementById('username').value;
let password = document.getElementById('password').value;
 

Resetting a Form:

To clear the input fields and reset the form to its initial state, you can use the reset() method.

document.getElementById('myForm').reset();