Created
November 22, 2019 14:14
-
-
Save carlitomurta/bc58d524b03d20c81bf0c22ac7c91db7 to your computer and use it in GitHub Desktop.
Pipe Angular para CEP/ZipCode
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Pipe, PipeTransform } from '@angular/core'; | |
@Pipe({ | |
name: 'zipCode' | |
}) | |
export class ZipCodePipe implements PipeTransform { | |
transform(value: string, args?: any): any { | |
if (value) { | |
value = value.replace(/\D/g, ''); | |
if (value.length > 8) { | |
value = value.substring(0, 8); | |
} | |
switch (value.length) { | |
case 3: | |
value = value.replace(/(\d{2})(\d+)/, '$1.$2'); | |
break; | |
case 4: | |
value = value.replace(/(\d{2})(\d+)/, '$1.$2'); | |
break; | |
case 5: | |
value = value.replace(/(\d{2})(\d+)/, '$1.$2'); | |
break; | |
case 6: | |
value = value.replace(/(\d{2})(\d{3})(\d+)/, '$1.$2-$3'); | |
break; | |
case 7: | |
value = value.replace(/(\d{2})(\d{3})(\d+)/, '$1.$2-$3'); | |
break; | |
case 8: | |
value = value.replace(/(\d{2})(\d{3})(\d+)/, '$1.$2-$3'); | |
break; | |
default: | |
return value; | |
} | |
} | |
return value; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment