Bootstrap 4使用自定义消息验证信用卡

时间:2018-04-04 13:52:22

标签: html5 twitter-bootstrap validation bootstrap-4 html5-validation

我正在使用bootstrap 4验证。如何验证信用卡号必须是数字,并且必须是16位数并显示相应的消息?

我想展示三条独立的消息。 1.如果输入注释,则“需要信用卡号”2.如果用户输入“xyz etc”,则“仅限数字”,3。如果用户输入少于16个号码,则显示消息为“”CC必须为16数字“。我们如何显示多个自定义消息?

请看小提琴。谢谢!

<html lang="en">
  <head> 
  </head>
  <body class="bg-light">

<form class="needs-validation" novalidate>
<div class="col-md-4 mb-3">
            <label for="cc-number">Credit card number</label>
            <input type="text" class="form-control" id="cc-number" placeholder="" required>
            <div class="invalid-feedback">
              Credit card number is required
            </div>
          </div>
<hr class="mb-4">
        <button class="btn btn-primary btn-lg btn-block" type="submit">Continue to checkout</button>
</form>
  <script>
  // Example starter JavaScript for disabling form submissions if there are invalid fields
  (function() {
    'use strict';

    window.addEventListener('load', function() {
      // Fetch all the forms we want to apply custom Bootstrap validation styles to
      var forms = document.getElementsByClassName('needs-validation');

      // Loop over them and prevent submission
      var validation = Array.prototype.filter.call(forms, function(form) {
        form.addEventListener('submit', function(event) {
          if (form.checkValidity() === false) {
            event.preventDefault();
            event.stopPropagation();
          }
          form.classList.add('was-validated');
        }, false);
      });
    }, false);
  })();
</script>
</body>

https://jsfiddle.net/6p3th7zz/10/

2 个答案:

答案 0 :(得分:2)

这个小提琴被打破了,因为jQuery并没有被包括在内。在输入中添加HTML5信用卡模式,Bootstrap 4将显示相应的invalid-feedback消息...

https://jsfiddle.net/uq4rb7zy/

 <form class="needs-validation" novalidate="" method="POST">
      <div class="col-md-4 mb-3">
         <label for="cc-number">Credit card number</label>
         <input type="text" class="form-control" id="cc-number" required="" pattern="[0-9]{16}">
         <div class="invalid-feedback">
            Credit card number is required and must be 16 digits
         </div>
      </div>
      <hr class="mb-4">
      <button class="btn btn-primary btn-lg btn-block" type="submit">Continue to checkout</button>
    </form>

编辑 Bootstrap不提供单独的验证消息。但是,您可以使用 HTML5验证API ...

执行此类操作
(function() {
  'use strict';
  window.addEventListener('load', function() {

    var forms = document.getElementsByClassName('needs-validation');
    // Loop over them and prevent submission
    var validation = Array.prototype.filter.call(forms, function(form) {
      form.addEventListener('submit', function(event) {
        if (form.checkValidity() === false) {
          event.preventDefault();
          event.stopPropagation();
          var ele = form.getElementsByTagName("input")
            for (var i = 0; i < ele.length; i++) {
                var msg = "", reason = ele[i].validity;
                if (reason.valueMissing) {
                   msg = ele[i].getAttribute("data-value-missing");
                }
                else if (reason.patternMismatch) {
                   msg = ele[i].getAttribute("data-pattern-mismatch");
                }
                else {
                    // other reason...
                }
                ele[i].nextElementSibling.innerText=msg;
            }
        }
        form.classList.add('was-validated');
      }, false);
    });
  }, false);
})();

然后在输入中添加data-value-missingdata-pattern-mismatch消息...

<input type="text" class="form-control" id="cc-number" required="" pattern="[0-9]{16}" data-value-missing="A credit card number is required" data-pattern-mismatch="The credit card number must be 16 digits">
<div class="invalid-feedback"></div>

Demo on Codeply

这将仅基于ValidityState提供不同的消息(例如,必需与模式)。它不会与模式失败的具体原因相匹配(例如,数字与字符)。

答案 1 :(得分:0)

我有这个脚本来限制电话号码和DNI(来自西班牙的文件标识)

        <script>
        // Funcion para limitar el numero de caracteres de un textarea o input
                function limitar(e, contenido, caracteres)
                {
                    var unicode=e.keyCode? e.keyCode : e.charCode;

                    if(unicode==8 || unicode==46 || unicode==13 || unicode==9 || unicode==37 || unicode==39 || unicode==38 || unicode==40)
                        return true;
                    // Si ha superado el limite de caracteres devolvemos false
                    if(contenido.length>=caracteres)
                        return false;
                    return true;
                }

        //Funcion ONLY NUMBERS
            function numbersonly(myfield, e, dec){
            var key;
            var keychar;

            if (window.event)
               key = window.event.keyCode;
            else if (e)
               key = e.which;
            else
               return true;
            keychar = String.fromCharCode(key);

            // control keys
            if ((key==null) || (key==0) || (key==8) || 
                (key==9) || (key==13) || (key==27) )
               return true;

            // numbers
            else if ((("0123456789").indexOf(keychar) > -1))
               return true;

            // decimal point jump
            else if (dec && (keychar == "."))
               {
               myfield.form.elements[dec].focus();
               return false;
               }
            else
               return false;
        }

        $(function(){           
            if (!Modernizr.inputtypes.date) {
            // If not native HTML5 support, fallback to jQuery datePicker


                $('input[type=date]').datepicker({
                    changeMonth: true,
                    changeYear: true,
                    yearRange: '-100:+0',
                    // Consistent format with the HTML5 picker
                    dateFormat : 'dd-mm-yy'
                    },
                    // Localization
                    $.datepicker.regional['es']
                );
            }
        });


    </script>

检查代码,确定它有效,然后你只需要在输入中调用这个函数

    <input type="text" class="form-control" name="inputDNI" placeholder="DNI" onKeyUp="return limitar(event,this.value,9)" onKeyDown="return limitar(event,this.value,9)" required>