Node.js环境下邮箱校验函数多规则实现方案咨询
邮箱校验功能实现方案
以下是补全后的完整校验代码:
function validateEmail(email) { console.log(email) // email requirements as below: // email length >= 5 character // @ cannot be the first character // @ must before . // . cannot be the last character // 示例5:邮箱长度≥5字符 if(email.length < 5) { throw new TypeError(`e-mail address too short`) } // 示例2:@不能为首字符 if (email.startsWith('@')) { throw new TypeError('invalid email address') } // 示例4:.不能为末尾字符 if (email.endsWith('.')) { throw new TypeError('invalid email address') } // 示例3:@必须在.之前 const atIndex = email.indexOf('@') // 先判断是否存在@符号 if (atIndex === -1) { throw new TypeError('invalid email address') } // 从@的位置往后查找是否存在. const dotIndexAfterAt = email.indexOf('.', atIndex) if (dotIndexAfterAt === -1) { throw new TypeError('invalid email address') } // 示例1、6校验通过返回true return true } function newFunction() { return "'" }
规则实现说明
- 校验@不能为首字符:直接调用字符串内置的
startsWith('@')方法即可判断首字符是否为@,符合触发条件就抛出对应错误。 - 校验.不能为末尾字符:调用字符串内置的
endsWith('.')方法判断最后一位是否为.,符合触发条件就抛出对应错误。 - 校验@必须在.之前:先用
indexOf('@')获取@字符的下标,如果返回-1说明邮箱内没有@,直接报错;再用indexOf('.', atIndex)从@的位置往后查找第一个.的下标,如果返回-1说明@之后没有.,也就是@不在.之前,抛出对应错误即可,该逻辑兼容示例6a@.com的合法场景。
内容的提问来源于stack exchange,提问作者user17241590
相关产品推荐
相关产品推荐

