【问题标题】:Bootstrap form validation for numbers only仅针对数字的引导表单验证
【发布时间】:2021-08-26 13:39:26
【问题描述】:

我是 PHP 新手,想创建一个如下所示的简单表单,并希望验证它并仅在正确验证后提交。

我面临电话验证问题,即使我输入字符,电话也会验证,我想验证数字和 + 号,例如 +1 12345678、+91 1234123123

我怎样才能只验证电话号码..

        <div class="col-md-12 mb-3">
          <input class="form-control" type="text" name="name" placeholder="Full Name" required>
          <div class="valid-feedback">Username field is valid!</div>
          <div class="invalid-feedback">Username field cannot be blank!</div>
        </div>

        <div class="col-md-12 mb-3">
          <input class="form-control" type="email" name="email" placeholder="E-mail Address" required>
          <div class="valid-feedback">Email field is valid!</div>
          <div class="invalid-feedback">Email field cannot be blank!</div>
        </div>

        <div class="col-md-12 mb-3">
          <input class="form-control" type="tel" name="tel" placeholder="Phone" required>
          <div class="valid-feedback">Phone field is valid!</div>
          <div class="invalid-feedback">Phone field cannot be blank!</div>
        </div>

        <div class="col-md-12 mb-3">
          <textarea name="message" id="message" placeholder="Your Message"></textarea>
        </div>

        <div class="col-md-12 mt-3">
          <label class="mb-3 mr-1" for="gender">I am interested in : </label>

          <input type="radio" class="btn-check" name="gender" id="male" autocomplete="off" required>
          <label class="btn btn-sm btn-outline-secondary" for="male">Call Back</label>

          <input type="radio" class="btn-check" name="gender" id="female" autocomplete="off" required>
          <label class="btn btn-sm btn-outline-secondary" for="female">Brochure</label>

          <input type="radio" class="btn-check" name="gender" id="secret" autocomplete="off">
          <label class="btn btn-sm btn-outline-secondary" for="secret">Price details</label>
        </div>

        <div class="form-button mt-3">
          <button id="submit" type="submit" class="btn btn-primary">Submit</button>
        </div>
      </form>
    </div>
  </div>
</div>   </div> </div>

(function () {
'use strict'
const forms = document.querySelectorAll('.requires-validation')
Array.from(forms)
  .forEach(function (form) {
    form.addEventListener('submit', function (event) {
      if (!form.checkValidity()) {
        event.preventDefault()
        event.stopPropagation()
      }

      form.classList.add('was-validated')
    }, false)
  })
})()
@import url('https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;700;900&display=swap');

*, body {
    font-family: 'Poppins', sans-serif;
    font-weight: 400;
    -webkit-font-smoothing: antialiased;
    text-rendering: optimizeLegibility;
    -moz-osx-font-smoothing: grayscale;
}

html, body {
    height: 100%;
    background-color: #152733;
    overflow: hidden;
}


.form-holder {
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
      text-align: center;
      min-height: 100vh;
}

.form-holder .form-content {
    position: relative;
    text-align: center;
    display: -webkit-box;
    display: -moz-box;
    display: -ms-flexbox;
    display: -webkit-flex;
    display: flex;
    -webkit-justify-content: center;
    justify-content: center;
    -webkit-align-items: center;
    align-items: center;
    padding: 60px;
}

.form-content .form-items {
    border: 3px solid #fff;
    padding: 40px;
    display: inline-block;
    width: 100%;
    min-width: 540px;
    -webkit-border-radius: 10px;
    -moz-border-radius: 10px;
    border-radius: 10px;
    text-align: left;
    -webkit-transition: all 0.4s ease;
    transition: all 0.4s ease;
}

.form-content h3 {
    color: #fff;
    text-align: left;
    font-size: 28px;
    font-weight: 600;
    margin-bottom: 5px;
}

.form-content h3.form-title {
    margin-bottom: 30px;
}

.form-content p {
    color: #fff;
    text-align: left;
    font-size: 17px;
    font-weight: 300;
    line-height: 20px;
    margin-bottom: 30px;
}


.form-content label, .was-validated .form-check-input:invalid~.form-check-label, .was-validated .form-check-input:valid~.form-check-label{
    color: #fff;
}

.form-content input[type=text], .form-content input[type=password], .form-content input[type=email], .form-content select {
    width: 100%;
    padding: 9px 20px;
    text-align: left;
    border: 0;
    outline: 0;
    border-radius: 6px;
    background-color: #fff;
    font-size: 15px;
    font-weight: 300;
    color: #8D8D8D;
    -webkit-transition: all 0.3s ease;
    transition: all 0.3s ease;
    margin-top: 16px;
}


.btn-primary{
    background-color: #6C757D;
    outline: none;
    border: 0px;
     box-shadow: none;
}

.btn-primary:hover, .btn-primary:focus, .btn-primary:active{
    background-color: #495056;
    outline: none !important;
    border: none !important;
     box-shadow: none;
}

.form-content textarea {
    position: static !important;
    width: 100%;
    padding: 8px 20px;
    border-radius: 6px;
    text-align: left;
    background-color: #fff;
    border: 0;
    font-size: 15px;
    font-weight: 300;
    color: #8D8D8D;
    outline: none;
    resize: none;
    height: 120px;
    -webkit-transition: none;
    transition: none;
    margin-bottom: 14px;
}

.form-content textarea:hover, .form-content textarea:focus {
    border: 0;
    background-color: #ebeff8;
    color: #8D8D8D;
}

.mv-up{
    margin-top: -9px !important;
    margin-bottom: 8px !important;
}

.invalid-feedback{
    color: #ff606e;
}

.valid-feedback{
   color: #2acc80;
}
<div class="form-body">
     
        <div class="row">
            <div class="form-holder">
                <div class="form-content">
                    <div class="form-items">
                        <h3>Register you interest</h3>
                        <p>Fill in the data below, we will get back to you!</p>
                        <form class="requires-validation" action="SubmitFORM.php" method="POST" novalidate>

                            <div class="col-md-12 mb-3">
                               <input class="form-control" type="text" name="name" placeholder="Full Name" required>
                               <div class="valid-feedback">Username field is valid!</div>
                               <div class="invalid-feedback">Username field cannot be blank!</div>
                            </div>

                            <div class="col-md-12 mb-3">
                                <input class="form-control" type="email" name="email" placeholder="E-mail Address" required>
                                 <div class="valid-feedback">Email field is valid!</div>
                                 <div class="invalid-feedback">Email field cannot be blank!</div>
                            </div>

                           <div class="col-md-12 mb-3">
                                 <input class="form-control" type="tel" name="tel" placeholder="Phone" required>
                                  <div class="valid-feedback">Phone field is valid!</div>
                                 <div class="invalid-feedback">Phone field cannot be blank!</div>
                           </div>

                           <div class="col-md-12 mb-3">
                              <textarea name="message" id="message" placeholder="Your Message"></textarea>
                           </div>


                           <div class="col-md-12 mt-3">
                            <label class="mb-3 mr-1" for="gender">I am interested in : </label>

                            <input type="radio" class="btn-check" name="gender" id="male" autocomplete="off" required>
                            <label class="btn btn-sm btn-outline-secondary" for="male">Call Back</label>

                            <input type="radio" class="btn-check" name="gender" id="female" autocomplete="off" required>
                            <label class="btn btn-sm btn-outline-secondary" for="female">Brochure</label>

                            <input type="radio" class="btn-check" name="gender" id="secret" autocomplete="off" >
                            <label class="btn btn-sm btn-outline-secondary" for="secret">Price details</label>
                            </div>             

                            <div class="form-button mt-3">
                                <button id="submit" type="submit" class="btn btn-primary">Submit</button>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    
    </div>
 

试图改变这个例子

【问题讨论】:

  • 我在这个问题中看到很多“我想要”,而不是很多“我试过”。
  • @miken32,从您的角度来看,您是正确的,是的,我确实尝试过,但是查看了不同的参考和示例,这使它看起来令人困惑,我仍在尝试,只有在尝试之后才能在这里这些错误持续了 3-4 小时......我现在才被困在验证中
  • 请添加您尝试过的内容以及得到的结果。是否有任何位置的任何字母通过或只是一些。

标签: javascript php html twitter-bootstrap validation


【解决方案1】:

您可以在输入标签中定义您想要的pattern,例如。

 <input class="form-control" type="tel" name="tel" placeholder="Phone" pattern="[+][0-9]{3}-[0-9]{2}-[0-9]{3}" required>

+123-45-678

同样,您可以根据自己的要求尝试类似的模式。希望这会有所帮助

【讨论】:

    【解决方案2】:

    我通过添加两个函数解决了这个问题,

    1. 我添加了 JS 功能,只允许电话字段中的数字
    2. 我还添加了international telephone numbers 用于 UX 的电话格式化,因为我还使用 IP 检测来自动选择国家代码以解决错误输入或错字,这主要发生在输入国家代码时,因为有些人使用输入没有国家代码的电话号码,有些输入 +XXX 有些输入 00XXX 作为国家代码..

    下面是CodePen上工作示例的链接

    (function () {
    'use strict'
    const forms = document.querySelectorAll('.requires-validation')
    Array.from(forms)
      .forEach(function (form) {
        form.addEventListener('submit', function (event) {
          if (!form.checkValidity()) {
            event.preventDefault()
            event.stopPropagation()
          }
    
          form.classList.add('was-validated')
        }, false)
      })
    })()
    
    function isNumber(evt) {
        evt = (evt) ? evt : window.event;
        var charCode = (evt.which) ? evt.which : evt.keyCode;
        if (charCode > 31 && (charCode < 48 || charCode > 57)) {
            return false;
        }
        return true;
    }
    
      var input1 = document.querySelector("#phone");
            // here, the index maps to the error code returned from getValidationError - see readme
            var errorMap = ["Invalid number", "Invalid country code", "Too short", "Too long", "Invalid number"];
    
             var iti1 = window.intlTelInput(input1, {
                utilsScript: "{{asset('js/utils.js')}}",
                initialCountry: "auto",
                preferredCountries: ['AE', 'US', 'UK', 'SA', 'QA', 'OM', 'IN'],
                setNumber: true,
                formatOnDisplay: true,
                nationalMode: true,
                geoIpLookup: function(success, failure) {
                    $.get("https://ipinfo.io", function() {}, "jsonp").always(function(resp) {
                        var countryCode = (resp && resp.country) ? resp.country : "";
                        success(countryCode);
                    });
                },
            });
    
            var reset = function() {
                input1.classList.remove("error");
            };
    
            // on blur: validate
            input1.addEventListener('keyup', function() {
                reset();
                if (input1.value.trim()) {
                    if (iti1.isValidNumber()) {
                        $('#phoneError').hide();
                        input1.classList.remove("is-invalid");
                        input1.classList.add("is-valid");
                        document.querySelector("#phoneinvalid").value = iti1.getNumber();
                    } else {
                        $('#phoneError').show();
                        input1.classList.remove("is-valid");
                        input1.classList.add("is-invalid");
                    }
                }
            });
    
            // on keyup / change flag: reset
            input1.addEventListener('change', reset);
            input1.addEventListener('keyup', reset);
    @import url('https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;700;900&display=swap');
    
    *, body {
        font-family: 'Poppins', sans-serif;
        font-weight: 400;
        -webkit-font-smoothing: antialiased;
        text-rendering: optimizeLegibility;
        -moz-osx-font-smoothing: grayscale;
    }
    
    html, body {
        height: 100%;
        background-color: yellow !important;
        overflow: hidden;
    }
    
    
    .form-holder {
          display: flex;
          flex-direction: column;
          justify-content: center;
          align-items: center;
          text-align: center;
          min-height: 100vh;
    }
    
    .form-holder .form-content {
        position: relative;
        text-align: center;
        display: -webkit-box;
        display: -moz-box;
        display: -ms-flexbox;
        display: -webkit-flex;
        display: flex;
        -webkit-justify-content: center;
        justify-content: center;
        -webkit-align-items: center;
        align-items: center;
        padding: 60px;
    }
    
    .form-content .form-items {
        border: 3px solid #fff;
        padding: 40px;
        display: inline-block;
        width: 100%;
        min-width: 540px;
        -webkit-border-radius: 10px;
        -moz-border-radius: 10px;
        border-radius: 10px;
        text-align: left;
        -webkit-transition: all 0.4s ease;
        transition: all 0.4s ease;
    }
    
    .form-content h3 {
        color: #fff;
        text-align: left;
        font-size: 28px;
        font-weight: 600;
        margin-bottom: 5px;
    }
    
    .form-content h3.form-title {
        margin-bottom: 30px;
    }
    
    .form-content p {
        color: #fff;
        text-align: left;
        font-size: 17px;
        font-weight: 300;
        line-height: 20px;
        margin-bottom: 30px;
    }
    
    
    .form-content label, .was-validated .form-check-input:invalid~.form-check-label, .was-validated .form-check-input:valid~.form-check-label{
        color: #fff;
    }
    
    .form-content input[type=text], .form-content input[type=password], .form-content input[type=email], .form-content select {
        width: 100%;
        padding: 9px 20px;
        text-align: left;
        border: 0;
        outline: 0;
        border-radius: 6px;
        background-color: #fff;
        font-size: 15px;
        font-weight: 300;
        color: #8D8D8D;
        -webkit-transition: all 0.3s ease;
        transition: all 0.3s ease;
        margin-top: 16px;
    }
    
    
    .btn-primary{
        background-color: #6C757D;
        outline: none;
        border: 0px;
         box-shadow: none;
    }
    
    .btn-primary:hover, .btn-primary:focus, .btn-primary:active{
        background-color: #495056;
        outline: none !important;
        border: none !important;
         box-shadow: none;
    }
    
    .form-content textarea {
        position: static !important;
        width: 100%;
        padding: 8px 20px;
        border-radius: 6px;
        text-align: left;
        background-color: #fff;
        border: 0;
        font-size: 15px;
        font-weight: 300;
        color: #8D8D8D;
        outline: none;
        resize: none;
        height: 120px;
        -webkit-transition: none;
        transition: none;
        margin-bottom: 14px;
    }
    
    .form-content textarea:hover, .form-content textarea:focus {
        border: 0;
        background-color: #ebeff8;
        color: #8D8D8D;
    }
    
    .mv-up{
        margin-top: -9px !important;
        margin-bottom: 8px !important;
    }
    
    .invalid-feedback{
        color: #ff606e;
    }
    
    .valid-feedback{
       color: #2acc80;
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/intl-tel-input/17.0.13/js/utils.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/intl-tel-input/17.0.13/js/intlTelInput.js"></script>
    <script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/intl-tel-input/17.0.13/css/intlTelInput.css" rel="stylesheet"/>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta2/dist/css/bootstrap.min.css" rel="stylesheet"/>
    <div class="form-body">
      <div class="row">
        <div class="form-holder">
          <div class="form-content">
            <div class="form-items">
              <h3>Register you interest</h3>
              <p>Fill in the data below, we will get back to you!</p>
              <form class="requires-validation" action="SubmitFORM.php" method="POST" novalidate>
    
                <div class="col-md-12 mb-3">
                  <input class="form-control" type="text" name="name" placeholder="Full Name" required>
                  <div class="valid-feedback">Username field is valid!</div>
                  <div class="invalid-feedback">Username field cannot be blank!</div>
                </div>
    
                <div class="col-md-12 mb-3">
                  <input class="form-control" type="email" name="email" placeholder="E-mail Address" required>
                  <div class="valid-feedback">Email field is valid!</div>
                  <div class="invalid-feedback">Email field cannot be blank!</div>
                </div>
    
                <div class="col-md-12 mb-3">
                  <input class="form-control" type="tel" id="phone" name="phone" placeholder="Phone" onkeypress="return isNumber(event)" required>
                  <div class="valid-feedback">Phone field is valid!</div>
                  <div class="invalid-feedback">Phone field cannot be blank!</div>
                </div>
    
                <div class="col-md-12 mb-3">
                  <textarea name="message" id="message" placeholder="Your Message"></textarea>
                </div>
    
                <div class="col-md-12 mt-3">
                  <label class="mb-3 mr-1" for="gender">I am interested in : </label>
    
                  <input type="radio" class="btn-check" name="gender" id="male" autocomplete="off" required>
                  <label class="btn btn-sm btn-outline-secondary" for="male">Call Back</label>
    
                  <input type="radio" class="btn-check" name="gender" id="female" autocomplete="off" required>
                  <label class="btn btn-sm btn-outline-secondary" for="female">Brochure</label>
    
                  <input type="radio" class="btn-check" name="gender" id="secret" autocomplete="off">
                  <label class="btn btn-sm btn-outline-secondary" for="secret">Price details</label>
                </div>
    
                <div class="form-button mt-3">
                  <button id="submit" type="submit" class="btn btn-primary">Submit</button>
                </div>
              </form>
            </div>
          </div>
        </div>
      </div>
    </div>

    【讨论】:

      猜你喜欢
      • 2020-02-29
      • 2017-11-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-11-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多