0

I have Face one problem in Angular2 & RegExp

This Package Used in Angular 2 https://github.com/text-mask/text-mask/

Documentation https://github.com/text-mask/text-mask/tree/master/angular2#readme

My Problem I can used 5-6 type Phone Format used

Like

  • (XXX) XXX XXXX

  • (XXX) XXX-XXXX

  • XXX-XXX-XXXX

  • XXX XXX XXXX
  • XXXXXXXXXX
  • XXXXX XXXXX

Above Package used Array Format

I have String this format

'(', /[1-9]/, /\d/, /\d/, ')', ' ', /\d/, /\d/, /\d/, '-', /\d/, /\d/, /\d/, /\d/

How I can add in Array Format

I can try this code

Code-1:

var phoneFormat:Array<string | RegExp>;
 var format="'(','/[1-9]/','/\d/','/\d/',')',' ','/\d/','/\d/','/\d/',' ','/\d/','/\d/','/\d/','/\d/'";

        var ArrayObj=format.split(',');

       for ( var i = 0; i < ArrayObj.length; i++ ) {
          phoneFormat.push(ArrayObj[i]); 
        }

Error Given:

Error: Uncaught (in promise): TypeError: Cannot read property 'push' of undefined
TypeError: Cannot read property 'push' of undefined

Code-2

 var format=['(','/[1-9]/','/\d/','/\d/',')',' ','/\d/','/\d/','/\d/',' ','/\d/','/\d/','/\d/','/\d/'];
       phoneFormat=format;

Code-2 No Error But masking not working

Harsh Patel
  • 6,334
  • 10
  • 40
  • 73
Jimit H.
  • 185
  • 1
  • 11

1 Answers1

0

As commented, you are getting following error:

TypeError: Cannot read property 'push' of undefined

because, you have not initialized the array.

var phoneFormat:Array<string | RegExp>; is just type definition. You will have to do var phoneFormat:Array<string | RegExp> = [];


Now

"'(','/[1-9]/','/\d/','/\d/',')',' ','/\d/','/\d/','/\d/',' ','/\d/','/\d/','/\d/','/\d/'"

is a string of formatted string. So when you split it, you will only get stringified string like "'('".

You will have to parse it. Following sample will help:

var phoneFormat: Array <string | RegExp> = [];
var format = "'(','/[1-9]/','/\d/','/\d/',')',' ','/\d/','/\d/','/\d/',' ','/\d/','/\d/','/\d/','/\d/'";

format.split(',').forEach(function(value){
  if(value.startsWith('\'/')) {
    phoneFormat.push(new RegExp(value.substring(2, value.length-2)));
  }
  else {
    phoneFormat.push(value.substring(1, value.length-1));
  }
});

console.log(phoneFormat)
Rajesh
  • 24,354
  • 5
  • 48
  • 79
  • i can success but i can type only "d" charcter(letter) no other character type :( – Jimit H. Sep 22 '17 at 06:13
  • i want only [0-9] number othre ASCII Charcter Allow how i can do this can you suggest me ?? – Jimit H. Sep 22 '17 at 06:15
  • You can use `input` event on textbox and check for new value. If new value satisfies regex, continue else set previous value – Rajesh Sep 22 '17 at 06:17
  • Thanks you i can success its big help to me last four day try it different code but not success – Jimit H. Sep 22 '17 at 06:18
  • You can refer: https://stackoverflow.com/questions/18156824/restricting-an-input-box-to-only-numbers-0-9 – Rajesh Sep 22 '17 at 06:18