Angular应用邮箱正则校验:排除指定特殊字符需求求助
Hey there! Let's get that email validation regex sorted for your Angular app. First, I noticed a small issue in your current pattern: you've used & which is an HTML entity, but in JavaScript regex, you should just use & directly — otherwise, your regex will treat a, m, p as allowed characters instead of the & symbol.
Now, onto your main requirement: blocking < > ( ) [ ] ; : , \. Your original regex already doesn't allow these characters in the local (before @) or domain (after @) parts, since they aren't included in the allowed character sets. But if you want to make this restriction explicit (and avoid accidentally allowing them later if you modify the allowed characters), we can adjust the regex to use a negative character class for the local part, which explicitly excludes the forbidden characters.
Here's the revised regex:
let emailPattern = /^[^<>()\[\];:,\\@]+@[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*$/i;
Let me break down what this does:
^[^<>()\[\];:,\\@]+: The local part of the email (before @). The^inside the brackets means "match any character that is NOT" the following: forbidden symbols + @ (since @ is the separator).@: The mandatory separator between local and domain parts.[a-z0-9]([a-z0-9-]*[a-z0-9])?: The first segment of the domain (e.g.,exampleinexample.com). Ensures the segment doesn't start or end with a hyphen.(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*: Matches additional domain segments (e.g.,.com,.co.uk), following the same hyphen rules.- The
iflag makes the regex case-insensitive, so it accepts uppercase letters too.
Test Cases
- Valid:
jane.doe+tag@example.co.uk,john_doe@test.org,bob-smith@company.com - Invalid (contains forbidden chars):
jane<doe@example.com,john(doe)@test.org,bob;smith@company.com
To use this in your Angular form, you can apply it to a FormControl like this:
import { FormControl, Validators } from '@angular/forms'; // Inside your component class emailControl = new FormControl('', [ Validators.required, Validators.pattern(emailPattern) ]);
This will ensure that any email containing your forbidden characters gets rejected during validation.
内容的提问来源于stack exchange,提问作者Dnyaneshwar Suryawanshi

