问题
I want to make mail validation with regex but it's not working.where is my mistake? It's normally working but when I put a regex control its never see yes the mail you key in is enable for this regex format.
Here is my code;
index.jsp
<head>
<title>Mail Control From Db</title>
<script type="text/javascript" src="jquery-1.2.6.min.js"></script>
<script type="text/javascript" src="check.js"></script>
</head>
<body>
<div align="left">
<form name="chkForm" id="chkForm" method="post" >
<table>
<tr>
<td>Email</td>
<td>
<input type="text" name="email" id="email" size="20" ></td>
<td>
<div id="emailInfo" align="left"></div>
</td>
</tr>
</table>
</form>
</div>
</body>
</html>
check.js
$(document).ready(function()
{
var myForm = $("#chkForm"), email = $("#email"), emailInfo = $("#emailInfo");
//send ajax request to check email
email.blur(function()
{
$.ajax({
type: "POST",
data: "email="+$(this).attr("value"),
url: "check.jsp",
beforeSend: function()
{
emailInfo.html("<font color='blue'>Kontrol Ediliyor..</font>");
},//end beforeSend: function()
success: function(data)
{
var reg = /\S+@\S+\.\S+/;
if (reg.test(email.val()))
{
var checkData = data.toString();
if(checkData == 0)
{
emailok = false;
emailInfo.html("<font color='red'>Mail in use</font>");
}//end if(checkData == 0)
else if(checkData == 1)
{
emailok = true;
emailInfo.html("<font color='green'>Mail is not in use</font>");
}//end else if(checkData == 1)
}//end if (reg.test(email.val()))
else
{
emailInfo.html("<font color='red'>ınvalid mail</font>");
}//end else
}// end success: function(data)
});
});//end email.blur(function()
});//end $(document).ready(function()
I had a problem in check.jsp. and solved it.
- problem is about regex.Regex was false.
- condition was false. i change it with if (reg.test(email.val())).
回答1:
Your regex only allows capital letters, so TEXT@EXAMPLE.COM would be okay but test@example.com not. You can change that either by adding the case-insensitive-flag to your regex
/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,6}$/i
or simply allow a-z in the regex itself
/^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,6}$/
But keep in mind that checking emails for validity is quite a difficult tasks to do, as the range of allowed mail-adresses is extremely broad and they even could contain special-chars like äüö etc. So your regex is not perfect, keep that in mind!
In PHP, I used this function for years and it always seemed to work.
Why exactly are you using .toString()
in this case? .test()
gives you an boolean which you can perfectly check with == false
- is there any reason why you want to convert this to a string?
来源:https://stackoverflow.com/questions/17692744/mail-validation-with-regex