正则一直是我的软肋,原来嫌麻烦不学,后来发现哪里都需要正则,痛定思痛,学起来~~
简单的练习了一下,实际用的时候还需要优化什么的。。。欢迎指教~
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>正则匹配</title>
</head>
<body>
<input type="email" value='' onblur="verifyFunc(event,'email')" id='ipt1' placeholder="邮箱">
<input type="tel" value='' onblur="verifyFunc(event,'tel')" id='ip2' placeholder="电话">
<input type="text" value='' onblur="verifyFunc(event,'url')" id='ipt3' placeholder="url">
</body>
<script text='javascript/text'>
function verifyFunc(event, type) {
var email = /^\w+[-+._]?\w+@\w+[+-._]?\.com|cn$/
var tel = /^(13|15|12|19)[0-9]{9}$/
var url = /^(http|https):\/\/(\w+[%=&\?\/\-\.]?\w*)+$/
if (type == 'email') {
!email.test(event.target.value) && alert('邮箱格式不正确!')
} else if (type == 'tel') {
!tel.test(event.target.value) && alert('电话号码不正确!')
} else if (type == 'url') {
!url.test(event.target.value) && alert('url不正确!')
}
}
</script>