Estes dias passei por um problema com isso.
Resolvi criar minha solucao e postar aqui pra galera dar uma olhada.
A formatação pode ser facilmente escolhida
Se alguem tiver novas ideias interessantes, por favor poste-as.
<html>
<head>
<title>Mascaras de formatação de campos</title>
<link rel="stylesheet" type="text/css" href="ext-3.3.0/resources/css/reset-min.css"/>
<link rel="stylesheet" type="text/css" href="ext-3.3.0/resources/css/ext-all.css"/>
<script type="text/javascript" src="ext-3.3.0/adapter/ext/ext-base.js"></script>
<script type="text/javascript" src="ext-3.3.0/src/locale/ext-lang-pt_BR.js"></script>
<script type="text/javascript" src="ext-3.3.0/ext-all.js"></script>
<script type="text/javascript">
/*
Autor: Luiz Augusto S. Prado
Lembre-se de nós quando utilizar estes metodos
*/
//**********************************************************************************************
//**********************************************************************************************
//**********************************************************************************************
// Metodos necessarios
/**
* SOLUÇÃO ELEGANTE de replaceAll em javascript
* fonte: http://codigofonte.uol.com.br/codigo/js-dhtml/strings/funcao-replaceall-em-javascript
*/
String.prototype.replaceAll = function(de, para)
{
var str = this;
var pos = str.indexOf(de);
while (pos > -1)
{
str = str.replace(de, para);
pos = str.indexOf(de);
}
return (str);
}
// Não é utilizada mas é bem iteressante ter guardada
/**
* Gets the caret (cursor) position of the specified text field.
* Valid positions are 0-oField.length.
* fonte: http://www.webdeveloper.com/forum/archive/index.php/t-74982.html
*/
function doGetCaretPosition (oField)
{
// Initialize
var iCaretPos = 0;
// IE Support
if (document.selection)
{
// Set focus on the element
oField.focus ();
// To get cursor position, get empty selection range
var oSel = document.selection.createRange ();
// Move selection start to 0 position
oSel.moveStart ('character', -oField.value.length);
// The caret position is selection length
iCaretPos = oSel.text.length;
}
// Firefox support
else if (oField.selectionStart || oField.selectionStart == '0')
iCaretPos = oField.selectionStart;
// Return results
return (iCaretPos);
}
/**
* Sets the caret (cursor) position of the specified text field.
* Valid positions are 0-oField.length.
* fonte: http://www.webdeveloper.com/forum/archive/index.php/t-74982.html
*/
function doSetCaretPosition (oField, iCaretPos)
{
// IE Support
if (document.selection)
{
// Set focus on the element
oField.focus ();
// Create empty selection range
var oSel = document.selection.createRange ();
// Move selection start and end to 0 position
oSel.moveStart ('character', -oField.value.length);
// Move selection start and end to desired position
oSel.moveStart ('character', iCaretPos);
oSel.moveEnd ('character', 0);
oSel.select ();
}
// Firefox support
else if (oField.selectionStart || oField.selectionStart == '0')
{
oField.selectionStart = iCaretPos;
oField.selectionEnd = iCaretPos;
oField.focus ();
}
}
//**********************************************************************************************
//**********************************************************************************************
//**********************************************************************************************
// inicio
/**
* FORMATADOR DE MASCARAS
*
* Autor: Luiz Augusto Prado
* Site pessoal: www.codigorapido.com.br
*
* Formata uma string para a mascara inserida
* @param {String} val é o value do textfield
* @param {String} str é a mascara
* @return JSON Object "{'result':String, 'difference':int}" : difference é a nova posicao do cursor
*/
format = function(val, str)
{
var valor=val;
var result="";
var temp = str.replaceAll("#"," ");
valor = valor.replaceAll(" ","");
for(var i=0; i<str.length;i++)
{
if(str[i]!='#')
valor = valor.replaceAll(str[i],"");
}
for(var i=0, y=0; i<valor.length && y<str.length; i++, y++)
{
if(str[y]!='#')
{
result+= str[y] + valor[i]
y++
}
else
{
result+= valor[i]
}
}
var difference = result.length
if(result.length!=str.length)
{
result+=temp.substring(result.length-1,str.length-1)
}
return {'result':result, 'difference':difference};
}
/**
* Componente TesteField
*
* Autor: Luiz Augusto Prado
* Site pessoal: www.codigorapido.com.br
*
* Componente TesteField
*/
TesteField = Ext.extend(Ext.form.TextField,
{
// apenas numeros inteiros e o ponto são permitidos
maskRe: /[0-9\.\/a-zA-Z]/,
// regex de validação do formato da string
maskFormat: /^[0-9]{3}.[0-9]{3}\/[a-zA-Z]{2}$/,
// mascara que aparecerá no campo
formatString: '###.###/##',
// mensagens
textvalorNulo: 'O valor não pode ser nulo!',
textformatoIncorreto:'O formato correto é iii.iii/ss' ,
textvalorInvalido:'valor invalido',
// função de validação. Para cpfs por exemplo.
// Basta sobrescrever esta função com sua funcao de validacao
// se não utilizar validacao faça textvalorInvalido=''
validatorFunction:function(v)
{
if(v=='100.001/Ab')
{
return true
}
else
{
return false
}
},
validationDelay:0,
enableKeyEvents: true,
validationEvent: true,
validator: function(v)
{
var temp = this.formatString.replaceAll("#"," ");
if(v==temp.substring(0,temp.length-1))
{
if(this.textvalorNulo!='') return this.textvalorNulo
else return true
}
else if( this.textformatoIncorreto!='' && this.maskFormat.test(v)!=true )
{
return this.textformatoIncorreto
}
else
{
// verifica se é um valor valido. No exemplo o valor é '100.001/Ab'
if(this.textvalorInvalido!='' && !this.validatorFunction(v))
{
return this.textvalorInvalido
}
else
{
return true
}
}
},
listeners:
{
buffer: 1,
blur: function()
{
validator(this.getValue())
},
keypress: function(f, e)
{
if(this.maskRe.test(String.fromCharCode(e.getCharCode())))
{
var fmt = format(this.getValue(), this.formatString )
this.setValue( fmt.result )
doSetCaretPosition(f.el.dom,fmt.difference)
}
validator(this.getValue())
}
},
onRender : function(ct, position)
{
TesteField.superclass.onRender.call(this, ct, position);
var fmt = format('', this.formatString )
this.setValue( fmt.result )
}
})
Ext.reg('testefield', TesteField );
//**********************************************************************************************
//**********************************************************************************************
//**********************************************************************************************
// Exemplo de uso
Ext.onReady(function ()
{
Ext.QuickTips.init();
var viewport = new Ext.Viewport
({
layout: 'border',
frame:true,
renderTo: Ext.getBody(),
items:
[{
id:'cpf',
x:130,
y:130,
xtype:'testefield'
}]
});
});
</script>
</head>
<body>
</body>
</html>