Wednesday, 22 January 2025

How to Validate Email Addresses in HTML Using the email Input Type and pattern Attribute?

type="email" Attribute

The type="email" attribute in an <input> element is specifically designed for entering email addresses. When this type is used, browsers automatically check the input to see if it contains a valid email format (i.e., includes an "@" symbol and a domain name). On mobile devices, it may trigger a keyboard optimized for entering email addresses, featuring symbols like @ and . for easier input.

 

pattern Attribute

The pattern attribute can be used to define custom rules (regular expressions) for the email input, allowing further control over the expected format. Although the email input type already performs basic validation, the pattern attribute allows for more precise validation (e.g., requiring a specific domain or restricting characters).

 

email-validation.html 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Email Validation Example</title>
</head>
<body>
    <form action="https://httpbin.org/post" method="POST">
        <label for="email">Email Address:</label><br>
        <input type="email" id="email" name="email" 
               pattern="[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,}$" 
               placeholder="example@domain.com" 
               required><br>
               &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
               <small>Enter a valid email like example@domain.com</small><br>
        <button type="submit">Submit</button>
    </form>
</body>
</html>

Above snippet generate below screen.

 


Click on Submit button by adding some invalid email, you can see a validation error.

 


1.   type="email": Ensures that the input field is for email addresses and performs a basic format check (must contain "@" and a domain).

2.   pattern="[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,}$": A more detailed regular expression that enforces specific rules for a valid email address:

·      [a-z0-9._%+-]+: The local part of the email (before the @), consisting of alphanumeric characters and certain symbols.

·      @[a-z0-9.-]+: Ensures the presence of an @ symbol followed by the domain part.

·      \.[a-z]{2,}$: Ensures a valid top-level domain (like .com or .org), with at least two letters.

 

Previous                                                    Next                                                    Home

No comments:

Post a Comment