• javascript进击(三)简介


    JavaScript 表单验证(可用来在数据被送往服务器前对 HTML 表单中的这些输入数据进行验证)

    被 JavaScript 验证的这些典型的表单数据有:

    用户是否已填写表单中的必填项目?

    用户输入的邮件地址是否合法?

    用户是否已输入合法的日期?

    用户是否在数据域 (numeric field) 中输入了文本?

    下面的函数用来检查用户是否已填写表单中的必填(或必选)项目。假如必填或必选项为空,那么警告框会弹出,并且函数的返回值为 false,否则函数的返回值则为 true(意味着数据没有问题):

    下面是连同 HTML 表单的代码:

     1 <html>
     2 <head>
     3 <script type="text/javascript">
     4 //邮箱验证
     5 function validate_required(field,alerttxt)
     6 {
     7 with (field)
     8   {
     9   if (value==null||value=="")
    10     {alert(alerttxt);return false}
    11   else {return true}
    12   }
    13 }
    14 //表单验证
    15 function validate_form(thisform)
    16 {
    17 with (thisform)
    18   {
    19   if (validate_required(email,"Email must be filled out!")==false)
    20     {email.focus();return false}
    21   }
    22 }
    23 </script>
    24 </head>
    25 
    26 <body>
    27 <form action="#" onsubmit="return validate_form(this)" method="post">
    28 Email: <input type="text" name="email" size="30">
    29 <input type="submit" value="Submit"> 
    30 </form>
    31 </body>
    32 
    33 </html>

    with(obj)作用就是将后面的{}中的语句块中的缺省对象设置为obj,那么在其后面的{}语句块中引用obj的方法或属性时可以省略obj.的输入而直接使用方法或属性的名称。

    下面的函数检查输入的数据是否符合电子邮件地址的基本语法

    意思就是说,输入的数据必须包含 @ 符号和点号(.)。同时,@ 不可以是邮件地址的首字符,并且 @ 之后需有至少一个点号:

     1 <html>
     2 <head>
     3 <script type="text/javascript">
     4 function validate_email(field,alerttxt)
     5 {
     6 with (field)
     7 {
     8 apos=value.indexOf("@")
     9 dotpos=value.lastIndexOf(".")
    10 if (apos<1||dotpos-apos<2) 
    11   {alert(alerttxt);return false}
    12 else {return true}
    13 }
    14 }
    15 
    16 function validate_form(thisform)
    17 {
    18 with (thisform)
    19 {
    20 if (validate_email(email,"Not a valid e-mail address!")==false)
    21   {email.focus();return false}
    22 }
    23 }
    24 </script>
    25 </head>
    26 
    27 <body>
    28 <form action="submitpage.htm"onsubmit="return validate_form(this);" method="post">
    29 Email: <input type="text" name="email" size="30">
    30 <input type="submit" value="Submit"> 
    31 </form>
    32 </body>
    33 
    34 </html>
  • 相关阅读:
    POJ3311Hie with the Pie(floyd传递+DP,状态压缩)
    POJ1185炮兵阵地(DP状态压缩)
    POJ3254Corn Fields (状态压缩or插头DP)
    eBPF Tracing 入门教程与实例
    因为 Java 和 Php 在获取客户端 cookie 方式不同引发的 bug
    DRDS 数据恢复重磅发布,全方位保障您的数据安全
    前沿 | 全球最具影响力开源数据库峰会开幕在即 阿里云精彩议题先睹为快
    MaxCompute 预付费标准版VS套餐版
    DTCC 2019 | 深度解码阿里数据库实现 数据库内核——基于HLC的分布式事务实现深度剖析
    从 Apache ORC 到 Apache Calcite | 2019大数据技术公开课第一季《技术人生专访》
  • 原文地址:https://www.cnblogs.com/tongx123/p/5092042.html
Copyright © 2020-2023  润新知