Ionic 3 CPF/CNPJ mask

Ionic 3 CPF/CNPJ mask

Content Index :

Ionic 3 CPF/CNPJ mask
Tag : html , By : rhinojosa
Date : January 12 2021, 08:33 AM

seems to work fine After a couple of days looking for a solution I create myself this one simple that works. So I would like to share with the community that solution, and if you want you can improve it and share again. DEMO
<form #loginForm="ngForm">
    <ion-label floating>CPF/CNPJ</ion-label>
    <ion-input [(ngModel)]="cpf_cnpj" (blur)="cpf_cnpj = format(cpf_cnpj)" name="cpf_cnpj"></ion-input>
  <button ion-button full type="submit" color="sicor" (tap)="login(signForm.value)">Login</button>
import { MenuController, NavParams, ModalController } from 'ionic-angular';
import { IonicPage, NavController } from 'ionic-angular';
import { AlertController } from 'ionic-angular';
import { Component } from '@angular/core';

  selector: 'page-login',
  templateUrl: 'login.html',
export class LoginPage {

  cpf_cnpj = '';
  pureResult: any;
  maskedId: any;
  val: any;
  v: any;

  public modalCtrl: ModalController, 
  private alertCtrl: AlertController,
  private menu: MenuController,
  public navCtrl: NavController, 

  ionViewDidEnter() {

  format(valString) {
    if (!valString) {
        return '';
    let val = valString.toString();
    const parts = this.unFormat(val).split(this.DECIMAL_SEPARATOR);
    this.pureResult = parts;
    if(parts[0].length <= 11){
      this.maskedId = this.cpf_mask(parts[0]);
      return this.maskedId;
      this.maskedId = this.cnpj(parts[0]);
      return this.maskedId;

unFormat(val) {
    if (!val) {
        return '';
    val = val.replace(/\D/g, '');

    if (this.GROUP_SEPARATOR === ',') {
        return val.replace(/,/g, '');
    } else {
        return val.replace(/\./g, '');

 cpf_mask(v) {
    v = v.replace(/\D/g, ''); //Remove tudo o que não é dígito
    v = v.replace(/(\d{3})(\d)/, '$1.$2'); //Coloca um ponto entre o terceiro e o quarto dígitos
    v = v.replace(/(\d{3})(\d)/, '$1.$2'); //Coloca um ponto entre o terceiro e o quarto dígitos
    //de novo (para o segundo bloco de números)
    v = v.replace(/(\d{3})(\d{1,2})$/, '$1-$2'); //Coloca um hífen entre o terceiro e o quarto dígitos
    return v;

 cnpj(v) {
    v = v.replace(/\D/g, ''); //Remove tudo o que não é dígito
    v = v.replace(/^(\d{2})(\d)/, '$1.$2'); //Coloca ponto entre o segundo e o terceiro dígitos
    v = v.replace(/^(\d{2})\.(\d{3})(\d)/, '$1.$2.$3'); //Coloca ponto entre o quinto e o sexto dígitos
    v = v.replace(/\.(\d{3})(\d)/, '.$1/$2'); //Coloca uma barra entre o oitavo e o nono dígitos
    v = v.replace(/(\d{4})(\d)/, '$1-$2'); //Coloca um hífen depois do bloco de quatro dígitos
    return v;

  public login(formData) { 
       ....you auth code here.

No Comments Right Now !

Boards Message :
You Must Login Or Sign Up to Add Your Comments .

Share : facebook icon twitter icon

Format textfield for CPF and CNPJ

Tag : ios , By : lamberms
Date : March 29 2020, 07:55 AM
around this issue How should I handle text formatting in iOS? I'm not talking about Currency or Decimal styles. Since iOS doesn't have setFormat(), it's kind of complicated. , You can use regular expressions to do formatting, like this:
NSRegularExpression *fmt = [NSRegularExpression
NSMutableString *str = [NSMutableString stringWithString:@"12345678910"];
[fmt replaceMatchesInString:str
                      range:NSMakeRange(0, str.length)

How to use phone mask in Angular 2 Ionic 2 RC 2

Tag : jquery , By : ChristianM
Date : March 29 2020, 07:55 AM
like below fixes the issue You can use https://igorescobar.github.io/jQuery-Mask-Plugin/
For Angular2 https://www.npmjs.com/package/ng2-input-mask
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<input type="text" id="phone"/>

<script type="application/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery.mask/1.14.10/jquery.mask.js"></script>

I can't add ng-cnpj directive using angular-formly

Tag : development , By : Joe Sweeney
Date : March 29 2020, 07:55 AM
should help you out I resolved it creating a custom type in formlyConfig. The following, my code solution:
(function () {
'use strict';

angular.module('app.runs', ['formly', 'formlyBootstrap', 'ngMask'])

.run(function (formlyConfig, $rootScope) {

  // mask from ngMask
    name: 'maskedInput',
    extends: 'input',
    defaultOptions: {
      ngModelAttrs: { // this is part of the magic... It's a little complex, but super powerful
        mask: { // the key "ngMask" must match templateOptions.ngMask
          attribute: 'mask' // this the name of the attribute to be applied to the ng-model in the template
        // applies the 'clean' attribute with the value of "true"
        'true': {
          value: 'clean'
      // this is how you hook into formly's messages API
      // however angular-formly doesn't ship with ng-messages.
      // You have to display these messages yourself.
      validation: {
        messages: {
          mask: 'Dado inválido!'

  // My CNPJ Custom Type
    name: 'rbCnpj',
    extends: 'maskedInput',
    wrapper: ['bootstrapLabel', 'bootstrapHasError'],
    template: '<div class="form-group">' +
                '<input ng-model="model[options.key]" class="form-control" ng-cnpj />' +
    defaultOptions: {
      templateOptions: {
        type: 'text',
        label: 'CNPJ',
        placeholder: '00.000.000/0000-00',
        mask: '99.999.999/9999-99',
        required: true



Ionic 3 Input Percentage Mask

Tag : angular , By : tlync
Date : March 29 2020, 07:55 AM
around this issue I'd like to hear any advice or recommendation on how to accomplish this. The requirement is to create an input mask directive that only allows the user to enter numbers, optionally 2 decimals, and it also has the % symbol inside the input field. Any idea, or if there is anything already built for this would be very appreciated, thanks in advance! , following Sam advice, solved with text-mask:
<input type="tel" [(ngModel)]="percent"
[textMask]="{mask: mask, pipe: percentage, guide:false}" />
mask(obj) {
    return [ /\d/, /\d|./, /\d|./, /\d/, /\d/ ];

percentage(value) {
    var num = value.replace('%', '');
    if (isNaN(num)) {
        if (num % 1 != 0) {
            num = parseFloat(num).toFixed(2);
        return num + '%';
    } else {
        return false;

Ionic 3 input mask

Tag : angular , By : µilad
Date : March 29 2020, 07:55 AM
Related Posts Related QUESTIONS :
  • Buttons overlapping when shrinking window
  • Stretch an element to the end of the automatically calculated grid, not just the explicit grid
  • What relation is there between Angular's <ng-content> and ShadowDOM
  • CSS background for div element is not working
  • CSS Marquee: multiple paragraphs overlaps
  • I want to align search bar to extreme right
  • Getting blank white space to the left of content inside pre tags
  • My viewer.html won't load any css and jss files
  • How to apply multiple styles to HTML to only part of a title?
  • Want to make text div transparent on a parallax area
  • Is there a way to make this ID plus descendants CSS rule less specific?
  • Is there a way to drop in a stylesheet to get a Material theme or similar for all form elements on the page?
  • How do I make a sideways L look in html/css?
  • Why won't the color #e67d22e1 display in Safari?
  • How to select specific tag's attribute value with xPath?
  • How to make div rows fill available height
  • How to fix text inside a block that grows
  • svg hexagon halftone pattern
  • How to edit a website's element's background colors using a chromium extention
  • What is the main tag in HTML5 ? How does it differ from body tag?
  • My image is flowing out from my div column. How I can fix it and made the image full-size into div
  • How to draw line in react
  • Why Transition css is not working in child selector css
  • How to modify materialize css select option?
  • How to center some text in a rectangle in CSS?
  • How do I equally space out css grid columns?
  • How to make sure all the parts of a macro are running correctly?
  • How to adjust the zoom of website at different browser at different screen size?
  • Can't set max height on child div properly
  • Why background color is not applying to DIV container?
  • Need to select the first-child
  • No space between attributes in buttons
  • How can I block google from crawling my page, but still let Baidu do it?
  • Rendering html content in matToolTip (Angular)
  • Embedding an iframe when iframe height is variable
  • How to use 'word-break: break-word' with link inside of text?
  • How I can animate circular progress bar from left to right?
  • Angular 6 - How can I hide a div onclick of outside of that div
  • How to fill an inline-block div with a solid color?
  • Form file doesn't align with rest of form
  • How to trim off left and right sides of image evenly as I reduce my screen size? (@media query)
  • How can I password protect a section of a static website?
  • Move a div up when I hover over it
  • Why is "align" not a valid attribute of div but still works?
  • Behavior with height/minHeight and display:flex
  • How can i change my h2 title to <p> text while keeping size and alignment?
  • Hover on the text to change size using CSS
  • How to keep a grid of cols without breaking on a new row?
  • Why is bottom: 0 not enough to move ::after content directly below main content?
  • Why does a React build need to be served? Why can't I just open it in the browser?
  • What is the proper way to target the tab key 'highlight' events on an html element?
  • How to Implement dot and line below the text in CSS?
  • DIVs not properly aligned
  • HTML 'for' tag not working for <p> but works on <label>
  • <p> element does not appear to be within parent <footer> element
  • Why flex container is smaller than its content
  • Center an image and a text in a div
  • .class with display: none -> .class:focus with display: block; causes links to not work
  • Best way to use a right pointing arrow in CSS animation
  • Angular 7 : Select tag doesn't display options
  • shadow
    Privacy Policy - Terms - Contact Us © scrbit.com