How To Use Regular Expression In Javascript
In This Javascript Tutorial we will See How To Use Regular Expression With Two Examples:
- Check If An Email Address Is Valid .
- Check If A Phone Number Is Valid .
In JS And Netbeans Editor .
Project Source Code:
<!DOCTYPE html>
<html>
<head>
<title>Javascript: Regex</title>
<meta charset="windows-1252">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<input type="text" id="mail"><br>
<span id="s_mail">-</span><br>
<input type="text" id="phone"><br>
<span id="s_phone">-</span><br>
<button onclick="check()" >Check</button>
<script>
// Email Like : mail@mail.com => ^([\w]+)@([\w]+)\.([\w]+)$
// Phone Number like : 0011 NNN NNN NNN => ^(0011)(([ ][0-9]{3}){3})$
function check(){
// Email
var mail = document.getElementById("mail").value,
regM = /^([\w]+)@([\w]+)\.([\w]+)$/,
isMailValid;
isMailValid = regM.test(mail);
if(isMailValid){
document.getElementById("s_mail").innerHTML = "Valid";
document.getElementById("s_mail").style.color = "green";
}else{
document.getElementById("s_mail").innerHTML = "Not Valid";
document.getElementById("s_mail").style.color = "red";
}
// Phone
var phone = document.getElementById("phone").value,
regP = /^(0011)(([-][0-9]{3}){3})$/,
isPhoneValid;
isPhoneValid = regP.test(phone);
if(isPhoneValid){
document.getElementById("s_phone").innerHTML = "Valid";
document.getElementById("s_phone").style.color = "green";
}else{
document.getElementById("s_phone").innerHTML = "Not Valid";
document.getElementById("s_phone").style.color = "red";
}
}
</script>
</body>
</html>
OUTPUT: