Essa função que estou mandando serve para validar e formatar CPF na hora que a pessoa esta escrevendo.
// DICIONARIO DE FUNCOES
// formato: 999.999.999-99
////////////////////////////////////////////////////////////////////////////////////
function FormataCpf(campo,tammax,teclapres) {
var tecla = teclapres.keyCode;
vr = event.srcElement.value;
vr = vr.replace( "/", "" );
vr = vr.replace( "/", "" );
vr = vr.replace( ",", "" );
vr = vr.replace( ".", "" );
vr = vr.replace( ".", "" );
vr = vr.replace( ".", "" );
vr = vr.replace( ".", "" );
vr = vr.replace( "-", "" );
vr = vr.replace( "-", "" );
vr = vr.replace( "-", "" );
vr = vr.replace( "-", "" );
vr = vr.replace( "-", "" );
tam = vr.length;
if (tam < tammax && tecla != 8){ tam = vr.length + 1 ; }
if (tecla == 8 ){ tam = tam - 1 ; }
if ( tecla == 8 || tecla >= 48 && tecla <= 57 || tecla >= 96 && tecla <= 105 ){
if ( tam <= 2 ){
event.srcElement.value = vr ; }
if ( (tam > 2) && (tam <= 5) ){
event.srcElement.value = vr.substr( 0, tam - 2 ) + '-' + vr.substr( tam - 2, tam ) ; }
if ( (tam >= 6) && (tam <= 8) ){
event.srcElement.value = vr.substr( 0, tam - 5 ) + '.' + vr.substr( tam - 5, 3 ) + '-' + vr.substr( tam - 2, tam ) ; }
if ( (tam >= 9) && (tam <= 11) ){
event.srcElement.value = vr.substr( 0, tam - 8 ) + '.' + vr.substr( tam - 8, 3 ) + '.' + vr.substr( tam - 5, 3 ) + '-' + vr.substr( tam - 2, tam ) ; }
if ( (tam >= 12) && (tam <= 14) ){
event.srcElement.value = vr.substr( 0, tam - 11 ) + '.' + vr.substr( tam - 11, 3 ) + '.' + vr.substr( tam - 8, 3 ) + '.' + vr.substr( tam - 5, 3 ) + '-' + vr.substr( tam - 2, tam ) ; }
if ( (tam >= 15) && (tam <= 17) ){
event.srcElement.value = vr.substr( 0, tam - 14 ) + '.' + vr.substr( tam - 14, 3 ) + '.' + vr.substr( tam - 11, 3 ) + '.' + vr.substr( tam - 8, 3 ) + '.' + vr.substr( tam - 5, 3 ) + '-' + vr.substr( tam - 2, tam ) ;}
}
}
//////////////////////////////////////////////////////////////////////////////////////////////////
forma de usar:
<input name="cpCNPJ" size="15" maxlength="80" onKeyPress="FormataCpf('cpCPFinformante',11,event)">