Bootstrap 4 validating credit card with custom messages

帅比萌擦擦* 提交于 2020-01-14 06:40:32

问题


I am using bootstrap 4 validation. How can I validate the credit card number must be numbers and must be 16 digits and show appropriate message?

I would like to show three separate messages. 1. If noting is entered, "Credit card number is required" 2. If user enters "xyz etc", then "numbers only" , 3. If user enters less than 16 numbers, then show message as ""CC must be 16 digits". How can we show multiple custom messages ?

Please see the fiddle. Thanks!

<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/


回答1:


The fiddle is broken because jQuery wasn't included. Add a HTML5 credit card pattern to the input, and Bootstrap 4 will display the appropriate invalid-feedback message...

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>

EDIT Bootstrap doesn't provide separate validation messages. However, you could do something like this with the HTML5 validation 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);
})();

And then on the input, add a data-value-missing and data-pattern-mismatch message...

<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

This will only provide different messages for based on ValidityState (eg. required vs. pattern). It isn't going to match specific reasons for pattern failure (eg. numbers vs characters).




回答2:


I have this script for limit the phone number and DNI (Document identity from Spain)

        <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>

Check the code, sure it works, then you just have to call the function in the input like this

    <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>


来源:https://stackoverflow.com/questions/49652831/bootstrap-4-validating-credit-card-with-custom-messages

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!