Welcome to today's session, where we will focus on form validation, a critically vital aspect of web development. Consider web forms as doorways that allow users to interact with web applications—whether registering for accounts or submitting requests. However, if we were to permit any input in these forms, chaos could ensue. Hence, we mitigate this issue by employing form validation. In this session, we'll master HTML attributes such as required
, type
, minlength
, maxlength
, min/max
, understand regular expressions (regex
), study the pattern
attribute, and learn how JavaScript validates forms.
HTML form input attributes give us the power to validate user input right in the browser, serving as our first line of defense in form validation. Let's dissect these attributes:
required
: This attribute ensures the user supplies input in a necessary field.type
: Specifies the kind of data the user must input (e.g., text, email, number, etc.).minlength
and maxlength
: These constraints limit the length of user input.min
and max
: These set the range for numerical input.title
: Displays advisory information about the element it belongs to, providing a hint to the user about how to fill out the input or what kind of data is expected.As an illustration, consider the following password input field, which enforces a password length minimum of 8 characters and a maximum of 20 characters while providing a tooltip when the user hovers over the input field. Note that with the required
attribute, the password field cannot be empty:
JavaScript1<input type="password" name="password" required minlength="8" maxlength="20" title="Your password should be 8-20 characters long.">
Here is a different number input field, where the min
and max
attributes specify that the permissible range for this input is between 1 and 10, inclusively:
JavaScript1<input type="number" name="quantity" min="1" max="10" title="Enter a number between 1 and 10">
Regular expressions, or regex
, are sequences of characters that form a search pattern used for text searching and text replacing operations. In HTML forms, regex
patterns allow us to match and validate various input strings (such as phone numbers, zip codes) using the pattern
attribute. This is best explained by the following example:
HTML, XML1<form action=""> 2 Phone number (xxx-xxxx): <input type="text" name="phone" pattern="[0-9]{3}-[0-9]{4}"> <!-- pattern="[0-9]{3}-[0-9]{4}" is regex that requires the form input to be "three numbers, a dash, and then four numbers". --> 3 <input type="submit"> 4</form>
This phone number form input requires "three numbers, a dash, and then four numbers" to submit the form.
While HTML form attributes are great for basic validation, JavaScript allows us to perform more complex conditions. It provides instant feedback to users, enhancing their experience and ensuring correct data submission. After accessing form data with JavaScript, we're able to validate it. It may be checking if text fields are empty, ensuring the length of a text input, or checking if a number is within a specific range. Let's dive into an example:
HTML, XML1<html> 2<body> 3 4<h2>JavaScript Form Validation</h2> 5<!-- The form below requires a text input field for the username. --> 6<form id="myForm"> 7 Username: <input type="text" name="username"> 8 <input type="submit"> 9</form> 10 11<script> 12// This JavaScript code validates the form input for the username field. 13document.getElementById("myForm").addEventListener("submit", function(event){ 14 // Access the value of the username field. 15 let val = document.forms["myForm"]["username"].value; 16 // Check if the username is between 3 and 15 characters. 17 if (val.length < 3 || val.length > 15) { 18 // If the username is not between 3 and 15 characters, an alert message pops up. 19 alert("Username must be 3-15 characters long"); 20 event.preventDefault(); 21 } 22}); 23</script> 24 25</body> 26</html>
This form demands a username length between 3 and 15 characters. If it falls outside this range, an alert message pops up to inform the user. But what if the user bypasses this message? This is where event.preventDefault()
comes into play.
event.preventDefault()
is a method that stops the default action of an element from happening. For a form, the default action is to send the form data and then reload the page. In our form, if the username is not between 3 and 15 characters, we don't want to submit the form. event.preventDefault()
stops the form from submitting, ensuring forms don't get submitted with incorrect or incomplete data.
So, using JavaScript for form validation enhances the user experience and ensures the correct data submission.
Today, we explored form validation by focusing on HTML attributes, regular expressions, the pattern
attribute, and JavaScript form validation. You should now be able to confidently apply these techniques to your projects, thus facilitating robust form validation.
Next, we will reinforce these skills with hands-on exercises. Remember, the key to mastery lies in practice. So, let's gear up and dive in!