- dikar
- 等级: 初级会员
- 性别:
- 文章: 40
- 积分: 50
- 来自: 杭州
|
遇到过很多应用要验证Email的格式,看过TOMCAT和JAVA的验证源代码,发现有些复杂,不过都是基于RFC2822作为验证指南的,其实验证主要考的是正则表达式的能力,还有就是你对Email的了解,最近看了《AJAX HACK》里面有个Email验证的例子,觉得很不错,所以贴出来与大家一起分享。
xml 代码
- /* Define an Email constructor*/
- function Email(e){
- this.emailAddr=e;
- this.message="";
- this.valid=false;
- }
-
- function validate(){
- //do a basic check for null, zero-length string, ".", "@",
- //and the absence of spaces
- if (this.emailAddr == null || this.emailAddr.length == 0 ||
- this.emailAddr.indexOf(".") == -1 ||
- this.emailAddr.indexOf("@") == -1 ||
- this.emailAddr.indexOf(" ") != -1){
- this.message="Make sure the email address does not contain any spaces "+
- "and is otherwise valid (e.g., contains the \"commercial at\" @ sign).";
- this.valid=false;
- return;
- }
-
- /*Get the user; they cannot begin or end with a "."
- Regular expression specifies: the group of characters before the @ symbol, which
- are made up of word characters, followed by zero or one period char,
- followed by at least 2 word characters. */
- regex=/(^\w{2,}\.?\w{2,})@/;
- _match = regex.exec(this.emailAddr);
-
- if ( _match){
- user=RegExp.$1;
- //alert("user: "+user);
- } else {
- this.message="Make sure the user name is more than two characters"+
- ", does not begin or end with a period (.), or is not otherwise "+
- "invalid!";
- this.valid=false;
- return;
- }
- //get the domain after the @ char
- //first take care of domain literals like @[19.25.0.1] however rare
- regex=/@(\[\d{1,3}\.\d{1,3}\.\d{1,3}.\d{1,3}\])$/;
- _match = regex.exec(this.emailAddr);
-
- if( _match){
- domain=RegExp.$1;
- //alert("domain: "+domain);
- this.valid=true;
- } else {
- /*the @ character followed by at least 2 chars that are not a period (.),
- followed by a period, followed by zero or one instances of at least two
- characters ending with a period, followed by two-three chars that are not periods */
- regex=/@(\w{2,}\.(\w{2,}\.)?[a-zA-Z]{2,3})$/;
- _match = regex.exec(this.emailAddr);
- if( _match){
- domain=RegExp.$1;
- } else {
- this.message="The domain portion of the email had less than 2 chars "+
- "or was otherwise invalid!";
- this.valid=false;
- return;
- }
- }//end domain check
- this.valid=true;
-
- }
-
- //Make validate() an instance method of the Email object
- Email.prototype.validate=validate;
声明:ITeye文章版权属于作者,受法律保护。没有作者书面许可不得转载。
|
返回顶楼 |
|
|
- zcfg
- 等级: 初级会员
- 性别:
- 文章: 25
- 积分: 40
- 来自: 北京
|
嗯 先收藏 顺便发一个用于验证email的正则表达式:
/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(txt)
|
返回顶楼 |
|
|
- yangjianxiang2
- 等级: 初级会员
- 性别:
- 文章: 29
- 积分: 30
- 来自: 上海
|
正则表达式 很 简单的
|
返回顶楼 |
|
|