w3pop.com :: 网络学院 :: JavaScript :: JS 校验
JavaScript can be used to validate input data in HTML forms before sending off the content to a server.
JS可以用来校验HTML表单提交给服务器的数据(是否符合规范)
JavaScript can be used to validate input data in HTML forms before sending off the content to a server.
JS可以用来校验HTML表单提交给服务器的数据(老外就是喜欢重复)
Form data that typically are checked by a JavaScript could be:
典型的JS检查表单数据有以下:
The function below checks if a required field has been left empty. If the required field is blank, an alert box alerts a message and the function returns false. If a value is entered, the function returns true (means that data is OK):
下面的函数检查了必添的内容有没空掉。如果空了的话就会出现警告信息并返回false。如果写了内容那就返回true(意思就是数据没问题)
function validate_required(field,alerttxt)
{
with (field)
{
if (value==null||value=="")
{alert(alerttxt);return false}
else {return true}
}
}
|
The entire script, with the HTML form could look something like this:
完整的脚本合起HTML表单:
<html>
<head>
<script type="text/javascript">
function validate_required(field,alerttxt)
{
with (field)
{
if (value==null||value=="")
{alert(alerttxt);return false}
else {return true}
}
}
function validate_form(thisform)
{
with (thisform)
{
if (validate_required(email,"Email must be filled out!")==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> |
The function below checks if the content has the general syntax of an email.
下面的函数会检查email内容的语法。
This means that the input data must contain at least an @ sign and a dot (.). Also, the @ must not be the first character of the email address, and the last dot must at least be one character after the @ sign:
意思就是输入的内容必须有起码一个@标记和一个点(.)而且@标记不能是email地址的第有个符号,点必须是在@标记后出现:
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}
}
}
|
The entire script, with the HTML form could look something like this:
完整的样子是这样(加入了HTML表单):
<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> |