js email验证

<html>
<head>
<script type="text/javascript">
function validate_email(field, alerttxt) {
	with(field) {
		apos = value.indexOf("@")
		dotpos = value.lastIndexOf(".")
		if(apos < 1 || dotpos - apos < 2) {
			alert(alerttxt);
			return false
		} else {
			return true
		}
	}
}

function validate_form(thisform) {
	with(thisform) {
		if(validate_email(email, "Not a valid e-mail address!") == false) {
			email.focus();
			return false
		}
	}
}
</script>
</head>

<body>
<form action="submitpage.htm"onsubmit="return validate_form(this);" method="post">
Email: <input type="text" name="email" size="30">
<input type="submit" value="Submit"> 
</form>
</body>

</html>

1、如何改进可以验证邮件地址 输入的数据包含 @ 和点(.)。@ 不可以是邮件地址的首字符,并且 @ 之后需有至少一个点号?
2、函数中的 with 是什么作用?
3、email.focus()获得焦点在这个地方什么作用

阅读 9.6k
1 个回答

第一个问题

验证邮箱格式最好使用正则表达式
首先阐述Email Address格式。
Email Address格式为 local-part@domain,Local Part和Domain Part两部分。
在Local Part中允许以下字符:

  • 大写或者小写的英文字母
  • 数字
  • 无限制的特殊字符 !#$%&'*+-/=?^_`{|}~
  • 句点(.),但是要求不能为第一个或者最后一个字符,也不能够连续出现两次以上
  • 有限制的特殊字符 空格和 "(),:;<>@[\] 它们必须出现在引号"之中,同时对于\"而言,它们在引号中还需要使用\转义,即"\\\""
  • 允许在开始和结尾处使用带有括号的注释,如john.smith(comment)@example.com(comment)john.smith@example.com等同于john.smith@example.com

Domain Part可以是hostname或者有方括号包围的ip地址。hostname只能由字母,数字以及-.组成。注释在Domain Part中也是被允许的。

代码实现
http://jsfiddle.net/cattail/bYZcL/

当前该代码存在的主要缺陷

  • 有无法通过一个正则表达式来检验,而是通过了两个正则表达式
  • 对于ip地址没有进行详细验证
  • 对emailjust"not"right@example.com的检验存在问题

第二个问题

with能够暂时改变语句中的作用域。它通过with后面的对象所拥有的属性拓展作用域。如field是一个input element,拥有属性value,因而在with语句中可以使用value来读取input中的值。
然而,并不推荐使用with,在Javascript的strict mode中,它是被禁止的。因为使用with语句使得Javascript代码的优化更加困难,因而会降低代码的运行速度。更中要的是,如果传入with的对象不具有在语句中使用的属性,该属性可能会从全局对象读取或者修改,因而造成难以察觉的错误。

第三个问题

聚焦使得当提示用户邮箱输入错误时,使得光标聚焦在email输入框中,便于用户修改。

参考资料

Wikipedia-email address:http://en.wikipedia.org/wiki/Email_ad...
Github gist地址:https://gist.github.com/4191834
Validate email address in Javascript http://stackoverflow.com/questions/46...
How far should one take e-mail address validation?http://programmers.stackexchange.com/...

合法的email地址

niceandsimple@example.com
very.common@example.com
a.little.lengthy.but.fine@dept.example.com
disposable.style.email.with+symbol@example.com
user@[IPv6:2001:db8:1ff::a0b:dbd0]
"much.more unusual"@example.com
"very.unusual.@.unusual.com"@example.com
"very.(),:;<>[]\".VERY.\"very@\\ \"very\".unusual"@strange.example.com
0@a
postbox@com (top-level domains are valid hostnames)
!#$%&'*+-/=?^_`{}|~@example.org
"()<>[]:,;@\\\"!#$%&'*+-/=?^_{}| ~ ? ^_{}|~.a"@example.org
""@example.org

非法email地址

Abc.example.com (an @ character must separate the local and domain parts)
Abc.@example.com (character dot(.) is last in local part)
Abc..123@example.com (character dot(.) is double)
A@b@c@example.com (only one @ is allowed outside quotation marks)
a"b(c)d,e:f;g<h>i[j\k]l@example.com (none of the special characters in this local part is allowed outside quotation marks)
just"not"right@example.com (quoted strings must be dot separated, or the only element making up the local-part)
this is"not\allowed@example.com (spaces, quotes, and backslashes may only exist when within quoted strings and preceded by a backslash)
this\ still\"not\\allowed@example.com (even if escaped (preceded by a backslash), spaces, quotes, and backslashes must still be contained by quotes)

来自<Javascript权威指南6>对于with的解读

5.7.1 with


In §3.10.3, we discussed the scope chainâa list of objects that are searched, in order,
to perform variable name resolution. The with statement is used to temporarily extend
the scope chain. It has the following syntax:

with (object)
    statement
This statement adds object to the front of the scope chain, executes statement, and
then restores the scope chain to its original state.
The with statement is forbidden in strict mode (see §5.7.3) and should be considered
deprecated in non-strict mode: avoid using it whenever possible. JavaScript code that
uses with is difficult to optimize and is likely to run more slowly than the equivalent
code written without the with statement.
The common use of the with statement is to make it easier to work with deeply nested
object hierarchies. In client-side JavaScript, for example, you may have to type expressions
like this one to access elements of an HTML form:

document.forms[0].address.value

If you need to write expressions like this a number of times, you can use the with
statement to add the form object to the scope chain:
with(document.forms[0]) {
    // Access form elements directly here. For example:
    name.value = "";
    address.value = "";
    email.value = "";
}
This reduces the amount of typing you have to do: you no longer need to prefix each
form property name with document.forms[0]. That object is temporarily part of the
scope chain and is automatically searched when JavaScript needs to resolve an identifier
such as address. It is just as simple, of course, to avoid the with statement and write
the code above like this:
var f = document.forms[0];
f.name.value = "";
f.address.value = "";
f.email.value = "";
Keep in mind that the scope chain is used only when looking up identifiers, not when
creating new ones. Consider this code:

with(o) x = 1;

If the object o has a property x, then this code assigns the value 1 to that property. But
if x is not defined in o, this code is the same as x = 1 without the with statement. It
assigns to a local or global variable named x, or creates a new property of the global
object. A with statement provides a shortcut for reading properties of o, but not for
creating new properties of o.
推荐问题
logo
101 新手上路
子站问答
访问
宣传栏