validator中isEmail是我们常用的验证email的方法,但你真的了解他的用法吗?
https://github.com/validatorjs/validator.js/blob/master/src/lib/isEmail.js isEmail(str [, options]) check if the string is an email.
options is an object which defaults to { allow_display_name: false, require_display_name: false, allow_utf8_local_part: true, require_tld: true, allow_ip_domain: false, domain_specific_validation: false }. options默认值为 { allow_display_name: false, require_display_name: false, allow_utf8_local_part: true, require_tld: true, allow_ip_domain: false, domain_specific_validation: false }.
If allow_display_name is set to true, the validator will also match Display Name . 默认为false,不允许 ”myname <address@gmail.com>“这样输入的,不能输入收件人名称,只能是邮箱。格式为address@gmail.com。 如果设置allow_display_name为true,则也允许输入类似于 ”myname <address@gmail.com>“的内容。显然默认是不允许这样输入的。
If require_display_name is set to true, the validator will reject strings without the format Display Name <email-address>. 默认为false,不强制要求显示收件人名称。 如果设置require_display_name为true,则表示必须有显示名称,格式必须是 ”myname <address@gmail.com>“ 。只是填与一个address@gmail.com,就会校验不通过。
If allow_utf8_local_part is set to false, the validator will not allow any non-English UTF8 character in email address’ local part. 默认为true,如果allow_utf8_local_part设置为false,验证程序将在电子邮件地址的本地部分中不允许使用任何非英语UTF8字符。
If require_tld is set to false, e-mail addresses without having TLD in their domain will also be matched. 默认为true,如果require_tld设置为false,则也将匹配在其域中没有TLD的电子邮件地址。
顶级域(或顶级域名;英语:Top-level Domain;英文缩写:TLD)是互联网DNS等级之中的最高级的域,它保存于DNS根域的名字空间中。顶级域名是域名的最后一个部分,即是域名最后一点之后的字母,例如在example.com这个域名中,顶级域是.com(或.COM),大小写视为相同。
If ignore_max_length is set to true, the validator will not check for the standard max length of an email. 默认为false,将校验email的最大长度,最大长度254个字符。 如果ignore_max_length设置为true,验证程序将不检查电子邮件的标准最大长度
If allow_ip_domain is set to true, the validator will allow IP addresses in the host part. 默认为false,不允许使用IP地址作为主机名。 如果allow_ip_domain设置为true,则验证器将允许主机部分中的IP地址。
If domain_specific_validation is true, some additional validation will be enabled, e.g. disallowing certain syntactically valid email addresses that are rejected by GMail. 默认为false, 如果domain_specific_validation 设置为true,将启用一些其他验证,例如,禁止某些语法有效的电子邮件地址被GMail拒绝。
最终也没有特别清楚这些参数的作用,所以自己写了一个自定义校验的,宽松一些的。
import { ValidatorConstraint, ValidatorConstraintInterface, ValidationArguments } from "class-validator"; @ValidatorConstraint({ name: "isEmailString", async: false }) export class isEmailString implements ValidatorConstraintInterface { validate(text: string, args: ValidationArguments) { let reg = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/; return reg.test(text); } defaultMessage(args: ValidationArguments) { // here you can provide default error message if validation failed return "($value) 不是一个合法的email。"; } } /** * 发送email验证码 */ export class sendEmailVerifyCodeDto { /** * email */ @Validate(isEmailString) readonly email: string; }