繁体   English   中英

JQuery的验证问题

[英]Validation issues with JQuery

iam在进行JQuery验证,如下所示:(我不太了解jquery)。

我无法完成以下任务:

  1. 仅允许使用字母a到z(小写),“-”(破折号或连字符)和“”(空格),
  2. 必须输入“-”(破折号)和“”(空格)字母,
  3. “-”或“”字母不能是输入的第一个字母或最后一个字母,
  4. “-”不得与“”的直接邻居或相邻(在此之前或之后),
  5. “-”或“”不能是其自身的直接邻居(相邻)。
  6. “电话”号码字段(4位区号,空格,7位本地号)


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
  <head>
  <script type="text/javascript" 
          src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js">
  </script>

  <script type="text/javascript" 
          src="http://jzaefferer.github.com/jquery-validation/jquery.validate.js">
  </script>

  <script>
    $(document).ready(function(){
      $("#commentForm").validate({
        onfocusout: function(element) { $(element).valid(); } ,
        rules: {
            fullname : {
              required: true,
              maxlength: 14,
            },                  
            email: {
              required: true,
              email: true
            }
        },
        messages: {
            fullname : {
              required: "Please specify your Full Name",
              maxlength:  "Please enter only upto 14 characters",
            },
            email: {
              required: "We need your email address to contact you",
              email: "Your email address must be in the format of name@domain.com"
            }
        }
      });
   });

   </script>

  </head>

  <body>

    <form id="commentForm" method="get" action="">

       <fieldset>

       <p>
         <label for="fullname">Full Name</label>
         <em>*</em><input id="fullname" name="fullname" size="25" class="required"  maxlength="14" />
       </p>


       <p>
         <label for="email">E-Mail</label>
         <em>*</em><input id="email" name="email" size="25"  class="required email" />
       </p>

     </fieldset>

  </form>
  </body>
</html>

请有人帮助我实现这一目标..?

使用正则表达式!!

  • 仅允许使用字母a到z(小写),“-”(破折号或连字符)和“”(空格)

    !/[^a-z0-9 -]/.test(input)

  • 必须输入“-”(破折号)和“”(空格)字母,

    / /.test(input) && /-/.test(input)

  • “-”或“”字母不能是输入的第一个字母或最后一个字母,

    !/^[ |-]|[ |-]$/.test(input)

  • “-”不得与“”的直接邻居或相邻(在此之前或之后),

  • “-”或“”不能是其自身的直接邻居(相邻)。

    !/ -|- |--| /.test(input)

  • “电话”号码字段(4位区号,空格,7位本地号)

    /^\\d{4} \\d{7}$/.test('1234 1234567')

如果满足条件,则每个表达式都返回true,否则返回false,如下所示:

var input = $('some-selector').value();
if(
  !/[^a-z0-9 -]/.test(input) &&
  / /.test(input) && /-/.test(input) &&
  !/^[ |-]|[ |-]$/.test(input) &&
  !/ -|- |--|  /.test(input) &&
  /^\d{4} \d{7}$/.test(input )
){
   //do something
}

更好的是,如果您要格式化电话号码,请删除所有非数字字符,

input = input.replace(/[^0-9]/,'')

数他们(他们必须是11)

input.length == 11

然后根据需要格式化它们。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM