cleave.js demo

cleave.js demo

by Ricardo Zambon

HTML

<script src="https://nosir.github.io/cleave.js/dist/cleave.min.js"></script>
<div class="container">
    <input class="cpfj" value="" placeholder="Enter your tax id number" />
</div>

CSS

* {
    box-sizing: border-box;
}
.container {
    width: 200px;
}
button {
    margin-bottom: 15px;
    width: 100%;
    height: 24px;
    outline: none;
    -webkit-appearance: none;
    border: 1px solid #e6e6e6;
    border-radius: 5px;
    background-color: #fff;
    font-size: 13px;
}
.input-credit-card {
    margin-bottom: 5px;
}
input {
    display: block;
    outline: none;
    -webkit-appearance: none;
    border: 1px solid #e6e6e6;
    border-radius: 5px;
    background-color: #fff;
    line-height: 30px;
    vertical-align: middle;
    height: 33px;
    width: 100%;
    font-size: 14px;
    padding: 0 8px;
    margin-bottom: 15px;
}

.input-numeral {
    text-align: right;
}

body {
    font-family: sans-serif;
}

a,
a:hover {
    color: #999;
}

a {
    font-size: 14px;
    margin-top: 20px;
}

JavaScript

var activeFormat;

$('.cpfj').on('input', function() {
    var oldValue = '';
    if ($(this).data('old_val') != undefined) { oldValue = $(this).data('old_val'); }

    var currentValue = this.value;
    if (activeFormat != null) { currentValue = activeFormat.getRawValue(); }
    
    if (oldValue.length != currentValue.length) {
      $(this).data('old_val', currentValue);
      
      if (activeFormat != null) {
        activeFormat.destroy();
        activeFormat = null;
      }

      if ($(this).val().length <= 14) {
        activeFormat = new Cleave('.cpfj', {
          numericOnly: true,
          blocks: [3, 3, 3, 3],
          delimiters : ['.', '.', '-']			
        });
      }
      else {
        activeFormat = new Cleave('.cpfj', {
          numericOnly: true,
          blocks: [2, 3, 3, 4, 2],
          delimiters : ['.', '.', '/', '-']
        });			
      }
    }
  });