Last active
October 10, 2017 21:45
-
-
Save andre-f-paggi/c610e95c98d5801e797ef77aa9312703 to your computer and use it in GitHub Desktop.
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
function Cep(cep) { | |
// constructor | |
this._cep = cep; | |
this.cepEhValido = cepEhValido; | |
this.comPontos = comPontos; | |
this.semPontos = semPontos; | |
if (cep) | |
_lancarExcecaoSeCepForInvalido(cep); | |
// functions | |
function cepEhValido(cep) { | |
cep = cep || this._cep; | |
var regexCep = /^\d{5}\-?\d{3}$/; | |
return regexCep.test(cep); | |
} | |
function comPontos(cep) { | |
cep = cep || this._cep; | |
_lancarExcecaoSeCepForInvalido(cep); | |
var cepSemPontos = cep.replace(/\D/gi, ""); | |
var cepComPontos = cepSemPontos.substring(0, 5) + "-" + cepSemPontos.substring(5, 8); | |
return cepComPontos; | |
} | |
function semPontos(cep) { | |
cep = cep || this._cep; | |
_lancarExcecaoSeCepForInvalido(cep); | |
return cep.replace(/\D/gi, ""); | |
} | |
function _lancarExcecaoSeCepForInvalido(cep) { | |
cep = cep || this._cep; | |
if (!cepEhValido(cep)) | |
throw new Error("Informe um CEP válido para formatação"); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment