前端开发笔记

JavaScript 邮箱验证 - 正则验证

2021-02-23  本文已影响0人  后除

一、RegExp

1.1 创建 RegExp 对象

new RegExp("必选,正则表达式","可选,匹配模式g,i,m")

1.2 RegExp 对象的方法

1.2.1 test()

var r1 = new RegExp('world');
console.log(r1.test('Hello, world!')); //true
console.log(r1.test('Hello, World!')); //false
var r2 = new RegExp('world', 'i'); //大小写不敏感
console.log(r2.test('Hello, World!')); //true
var r3 = new RegExp(/world/i); //简写
console.log(r3.test('Hello, World!')); //true

1.2.2 exec()

var r1 = new RegExp('world');
console.log(r1.exec('Hello, world!')); //['world']
console.log(r1.exec('Hello, World!')); //null
var r2 = new RegExp('world', 'i'); //大小写不敏感
console.log(r2.exec('Hello, World!')); //['world']
var r3 = new RegExp(/world/i); //简写
console.log(r3.exec('Hello, World!')); //['world']
var r4 = new RegExp('o');
console.log(r4.exec('Hello, World!')); //['o']
var r5 = new RegExp('o', 'gi');
console.log(r5.exec('Hello, WOrld!')); //['o']
console.log(r5.lastIndex); //5 匹配文本的第一个字符的位置,o为4,下一个位置为5
console.log(r5.exec('Hello, WOrld!')); //['O'] 匹配完第一个o后调用继续匹配
console.log(r5.lastIndex); //9
console.log(r5.exec('Hello, WOrld!')); //null 匹配不到返回null
console.log(r5.lastIndex); //0 lastIndex重置为0

1.2.3 complie()

var r1 = new RegExp('world');
console.log(r1.exec('Hello, world!')); //['world']
r1.compile('o');
console.log(r1.exec('Hello, World!')); //['o']
r1.compile('m');
console.log(r1.exec('Hello, World!')); //null
var r2 = new RegExp('world');
console.log(r2.test('Hello, world!')); //true
r2.compile('mazey');
console.log(r2.test('Hello, world!')); //false

二、正则表达式

三、示例

<form action="">
    输入:
    <input type="text" name="mazey" id="mazey" placeholder="请输入邮箱">
    <input type="button" value="验证" onclick="check();">
</form>

<script>
function check(){
    var reg = new RegExp("^[a-z0-9]+([._\\-]*[a-z0-9])*@([a-z0-9]+[-a-z0-9]*[a-z0-9]+.){1,63}[a-z0-9]+$"); //正则表达式
    var obj = document.getElementById("mazey"); //要验证的对象
    if(obj.value === ""){ //输入不能为空
        alert("输入不能为空!");
        return false;
    }else if(!reg.test(obj.value)){ //正则验证不通过,格式不对
        alert("验证不通过!");
        return false;
    }else{
        alert("通过!");
        return true;
    }
}
</script>

附录

阅读原文:https://blog.mazey.net/589.html

上一篇 下一篇

猜你喜欢

热点阅读