javascript
用正则表达式判断Email的格式是否正确:
<scriptlanguage=javascript>
function checkEmail(el)//用正则表达式判断
{
varregu ="^(([0-9a-zA-Z]+)|([0-9a-zA-Z]+[_.0-9a-zA-Z-]*[0-9a-zA-Z-]+))@([a-zA-Z0-9-]+[.])+([a-zA-Z]|net|NET|asia|ASIA|com|COM|gov|GOV|mil|MIL|org|ORG|edu|EDU|int|INT|cn|CN|cc|CC)$"
varre = new RegExp(regu);
if(el.search(re) == -1)
{
returntrue; //非法
}
returnfalse;//正确
}
functionchecklogin()
{
var obj =document.getElementById(’emailid’);
if(checkEmail(obj.value))
{
alert("E-mail格式不正确,请检查!");
obj.focus();
returnfalse;
}
}
</script>
<formname="myform" action="" onSubmit="returnchecklogin();" method="post">
Email:
<inputname="email" id="emailid" type="text"size="25" />
<input name="submit"type="submit" value="登陆"/></form>
用JS判断Email格式是否符合要求:
<scriptlanguage="javascript">
function checkemail()
{
if(document.myform.email.value.charAt(0)=="." ||document.myform.email.value.charAt(0)=="@"||document.myform.email.value.indexOf(’@’, 0) == -1 ||document.myform.email.value.indexOf(’.’, 0) == -1 ||document.myform.email.value.lastIndexOf("@")==document.myform.email.value.length-1||document.myform.email.value.lastIndexOf(".")==document.myform.email.value.length-1)
{
alert("Email的格式不正确!");
document.myform.email.focus();
returnfalse;
}
return true;
}
</script>
<formname="myform" action="" onSubmit="returncheckemail();" method="post">
Email:
<inputname="email" id="emailid" type="text"size="25" />
<input name="submit"type="submit" value="登陆"/></form>
Java
publicclassCheckEmail {
publicstaticbooleancheckEmail(String email){
//验证邮箱的正则表达式
Stringformat = "\\p{Alpha}\\w{2,15}[@][a-z0-9]{3,}[.]\\p{Lower}{2,}";
if(email.matches(format)){
returntrue; //邮箱名合法,返回true
}else{
returnfalse; // 邮箱名不合法,返回false
}
}
publicstaticvoidmain(String[] args) {
Stringemail = "cc**365@163.com"; //需要进行验证的邮箱
if(CheckEmail.checkEmail(email)){ // 验证邮箱
System.out.println(email+"\n是合法的邮箱名。");
}else{
System.out.println(email+"\n不是合法的邮箱名。");
}
}
}