bootstrap中的表单验证3

时间:2018-03-27 11:32:34

标签: javascript html5 twitter-bootstrap

我在bootstrap 3中有一个表单。我可以使用has-error类进行基本验证。我如何检查特定的用户输入,如?

  1. 用户只能输入字符作为名字和姓氏
  2. 用户只能输入数字/数字作为电话号码
  3. 用户只能输入有效的电子邮件字符。
  4. 还有什么可以输出更加用户友好的验证错误消息。 我是bootstrap的新手,非常感谢任何帮助。这是我的代码

     <!DOCTYPE html>
    <html lang="en">
    
    <head>
      <meta charset="utf-8">
      <meta http-equiv="X-UA-Compatible" content="IE=edge">
      <link href="css/bootstrap.min.css" rel="stylesheet">
    </head>
    
    <body>
    
      <form method="post" id="contactform" action="" role="form">
        <div class="form-group">
    
          <div class="input-group">
            <span class="input-group-addon transparent"><span class="glyphicon 
            glyphicon-user"></span></span>
            <input class="form-control" placeholder="First Name" name="firstname" type="text" id="firstname" />
          </div>
        </div>
    
        <div class="form-group">
    
          <div class="input-group">
            <span class="input-group-addon transparent"><span class="glyphicon 
            glyphicon-user"></span></span>
            <input class="form-control" placeholder="Last Name" name="lastname" type="text" id="lastname" />
          </div>
        </div>
    
        <div class="form-group">
    
          <div class="input-group">
            <span class="input-group-addon transparent"><span class="glyphicon 
              glyphicon-envelope"></span></span>
            <input class="form-control" placeholder="Email" name="email" type="text" id="email" />
          </div>
        </div>
    
        <div class="form-group">
    
          <div class="input-group">
            <span class="input-group-addon transparent"><span class="glyphicon 
              glyphicon-earphone"></span></span>
            <input class="form-control" placeholder="Phone Number" name="phone" type="text" id="phone" />
          </div>
        </div>
    
        <button type="button" id="contactbtn" class="btn btn- 
        primary">Submit</button>
      </form>
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js">
      </script>
    
      <script src="js/bootstrap.min.js"></script>
    
    
      <script type="text/javascript">
        function validateText(id) {
    
          if ($("#" + id).val() == null || $("#" + id).val() == "") {
            var div = $("#" + id).closest("div");
            div.addClass("has-error");
            return false;
    
          } else {
    
            var div = $("#" + id).closest("div");
            div.removeClass("has-error");
            return true;
          }
        }
    
        $(document).ready(
          function() {
            $("#contactbtn").click(function() {
    
              if (!validateText("firstname")) {
                return false;
              }
    
              if (!validateText("lastname")) {
                return false;
              }
    
              if (!validateText("email")) {
                return false;
              }
              if (!validateText("phone")) {
                return false;
              }
              $("form#contactform").submit();
            });
          }
        );
      </script>
    
    </body>
    
    </html>
    

5 个答案:

答案 0 :(得分:1)

HTML输入字段有一个名为pattern的属性,您可以使用该属性确保具有正则表达式的特定输入。

<input class="form-control" placeholder="First Name"
name="firstname" type="text" id="firstname" pattern="^\w*$" />
...
<input class="form-control" placeholder="Last Name" name="lastname" 
type="text" id="lastname" pattern="^\w*$" />
...
<input class="form-control" placeholder="Email" name="email" 
type="text" id="email" pattern="^[^@\\s]+@[^@\\s]+\\.[^@\\s]+$" />
...
<input class="form-control" placeholder="Phone Number" name="phone" 
type="text" id="phone" pattern="^\d*$" />

这只是一个简单的示例电子邮件正则表达式。电子邮件还有很多其他正则表达式。

答案 1 :(得分:0)

您可以使用jquery boostrap验证。这很容易。您可以按照以下方式操作 answer

答案 2 :(得分:0)

如果你想使用别的东西,你可能需要调整一些东西。但这最好以引导方式使用。

&#13;
&#13;
var showErrorSuccess = function(element, status) {
  if (status === false) {
    element.parent().next().removeClass('hidden').parent().addClass('has-error');
    return false;
  }
  element.parent().next().addClass('hidden').parent().removeClass('has-error').addClass('has-success');
};

var validate = function() {
  event.preventDefault();
  //validate name
  var name = $('#firstname').val();
  if (name.length < 3) {
    return showErrorSuccess($('#firstname'), false);
  }
  showErrorSuccess($('#firstname'));

  var lastname = $('#lastname').val();
  if (lastname.length < 3) {
    return showErrorSuccess($('#lastname'), false);
  }
  showErrorSuccess($('#lastname'));

  //validate email
  var email = $('#email').val(),
    emailReg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/
  if (!emailReg.test(email) || email == '') {
    return showErrorSuccess($('#email'), false);
  }
  showErrorSuccess($('#email'));

  //validate phone
  var phone = $('#phone').val(),
    intRegex = /[0-9 -()+]+$/;
  if ((phone.length < 6) || (!intRegex.test(phone))) {
    return showErrorSuccess($('#phone'), false);
  }
  showErrorSuccess($('#phone'));
};
&#13;
body>form {
  padding-left: 15px;
  padding-top: 15px;
  padding-right: 15px;
}
&#13;
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
</head>

<body>
  <form class="form-vertical" method="post" id="contactform" onSubmit="javascript:validate()" action="" role="form">
    <div class="form-group">
      <div class="input-group">
        <span class="input-group-addon transparent"><span class="glyphicon 
    glyphicon-user"></span></span>
        <input class="form-control" placeholder="First Name" name="firstname" type="text" id="firstname" />
      </div>
      <p class="help-block hidden">Please enter a name 3 characters or more.</p>
    </div>
    <div class="form-group">
      <div class="input-group">
        <span class="input-group-addon transparent"><span class="glyphicon 
    glyphicon-user"></span></span>
        <input class="form-control" placeholder="Last Name" name="lastname" type="text" id="lastname" />
      </div>
      <p class="help-block hidden">Please enter a name 3 characters or more.</p>
    </div>
    <div class="form-group">
      <div class="input-group">
        <span class="input-group-addon transparent"><span class="glyphicon 
      glyphicon-envelope"></span></span>
        <input class="form-control" name="email" placeholder="Email" type="email" id="email" />
      </div>
      <p class="help-block hidden">Please enter a valid email address.</p>
    </div>
    <div class="form-group">
      <div class="input-group">
        <span class="input-group-addon transparent"><span class="glyphicon 
      glyphicon-earphone"></span></span>
        <input class="form-control" name="phone" placeholder="Phone Number" type="phone" id="phone" />
      </div>
      <p class="help-block hidden">Please enter a valid phone number.</p>
    </div>
    <button type="submit" class="btn btn-primary">Submit</button>
  </form>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</body>

</html>
&#13;
&#13;
&#13;

答案 3 :(得分:0)

使用正确的输入type以及声明pattern属性的组合可能会排除对任何特殊JavaScript的需求。

1)用户只能输入字符作为名字和姓氏

为此,您需要依赖<input type="text">,默认情况下基本上允许任何内容。因此,我们需要应用pattern将此字段限制为仅限字母:

<input type="text" pattern="[A-Za-z]+">

2)用户只能输入数字/数字作为电话号码

根据您的需要,这可能就像使用正确的输入type

一样简单

<input type="tel">

https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/tel

由于不同的国家/地区有不同的模式,因此您可能希望通过添加pattern属性来改进此模式。

<input type="tel" pattern="^[0-9\-\+\s\(\)]*$">

这将允许您的数字输入更灵活,接受破折号和括号,允许用户指定+ DIGIT国家/地区代码等。

3)用户只能输入有效的电子邮件字符。

再次使用正确的输入type将大大简化您的验证工作:

<input type="email">

https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/email

这是另一个可能有点“模糊”的问题。当您比较某些输入类型时,因为它实际上只是查找handle@domain.extension。您可以使用上面的Mozilla开发人员工具包链接了解有关其特定验证模式的更多信息。

答案 4 :(得分:-1)

通过使用自定义jquery / javascript代码

,使用表单验证是一个简单而且最好的概念

<!DOCTYPE html>
 <html lang="en">
 <head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
 </head>
  <body>

 <form method="post" id="contactform" action="" role="form">
 <div class="form-group">

    <div class="input-group">
        <span class="input-group-addon transparent"><span class="glyphicon 
    glyphicon-user"></span></span>
        <input class="form-control" placeholder="First Name" 
    name="firstname" type="text" id="firstname" />
    </div>
</div>

<div class="form-group">

    <div class="input-group">
        <span class="input-group-addon transparent"><span class="glyphicon 
    glyphicon-user"></span></span>
        <input class="form-control" placeholder="Last Name" name="lastname" 
   type="text" id="lastname" />
    </div>
   </div>

    <div class="form-group">

    <div class="input-group">
        <span class="input-group-addon transparent"><span class="glyphicon 
      glyphicon-envelope"></span></span>
        <input class="form-control" name="email" placeholder="Email"    type="email" id="email" />
    </div>
   </div>

<div class="form-group">

    <div class="input-group">
        <span class="input-group-addon transparent"><span class="glyphicon 
      glyphicon-earphone"></span></span>
        <input class="form-control" name="phone" placeholder="Phone Number" 
     type="phone" id="phone" />
    </div>
</div>

    <button type="button" id="contactbtn" onclick="validateText();" class="btn btn- 
primary">Submit</button>
</form>
<script 
 src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"> 
 </script>

<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>


 <script type="text/javascript">

  function validateText(id){
   //validate name
var name = $('input[id="firstname"]').val();
if (name.length < 3)
{
    alert('Please enter a name 3 characters or more.');
    return false;
}
var lastname = $('input[id="lastname"]').val();
if (name.length < 3)
{
    alert('Please enter a name 3 characters or more.');
    return false;
}

//validate email
var email = $('input[id="email"]').val(),
    emailReg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/
if(!emailReg.test(email) || email == '')
{
     alert('Please enter a valid email address.');
     return false;
}

//validate phone
var phone = $('input[id="phone"]').val(),
    intRegex = /[0-9 -()+]+$/;
if((phone.length < 6) || (!intRegex.test(phone)))
{
     alert('Please enter a valid phone number.');
     return false;
}
 }

 
 </script>

  </body>
  </html>