显然我的剧本是对的,有人可以帮我这个吗?当我看到控制台时,会显示消息Cannot call method 'toString' of undefined
。
ID选择器可能有问题吗?我可以只使用一个函数而不是使用一个函数进行验证而另一个函数可以运行我的函数吗?
/* ==== CPF Validator ==== */
function validar_cpf(cpf)
{
regex = /\./g;
cpf = cpf.toString().replace(regex,'');
cpf_split = cpf.split('-');
numero = cpf_split[0];
dv = cpf_split[1];
numero_init = numero.toString() + dv.toString();
if(numero_init.length < 11)
return false
var somatorio = 0;
for(i = 10, n = 0; i >= 2 ; i--, n++){
m = numero.charAt(n) * i;
somatorio += m;
}
dv1 = somatorio / 11;
dv1 = parseInt(dv1);
resto = somatorio % 11;
if(resto < 2)
dv1 = 0;
else
dv1 = Math.abs(11 - resto);
numero += dv1.toString();
somatorio = 0;
for(i = 11, n= 0; i >= 2 ; i--, n++ ){
m = numero.charAt(n) * i;
somatorio += m;
}
resto = somatorio % 11;
if(resto < 2)
dv2 = 0;
else
dv2 = 11 - resto;
numero += dv2.toString();
if(numero == numero_init)
return true;
else
return false;
}
function ValidaCpf()
{
if (validar_cpf(cpf))
{
document.getElementById('first-cpf').classList.add('hide');
document.getElementById('second-cpf').classList.remove('hide');
document.getElementById('cpf').classList.add('form_invalido');
document.getElementById('cpf').classList.remove('form_valido');
}
else {
document.getElementById('first-cpf').classList.remove('hide');
document.getElementById('second-cpf').classList.add('hide');
document.getElementById('cpf').classList.remove('form_invalido');
document.getElementById('cpf').classList.add('form_valido');
}
}
答案 0 :(得分:0)
我找到了解决方案
/* ==== CPF Validator ==== */
function ValidaCpf(input) {
var value = input.value,
result = true,
invalids = new Array(
'111.111.111-11',
'222.222.222-22',
'333.333.333-33',
'444.444.444-44',
'555.555.555-55',
'666.666.666-66',
'777.777.777-77',
'888.888.888-88',
'999.999.999-99',
'000.000.000-00',
'11111111111',
'22222222222',
'33333333333',
'44444444444',
'55555555555',
'66666666666',
'77777777777',
'88888888888',
'99999999999',
'00000000000'
);
for( var i = 0; i<invalids.length; i++) {
if( invalids[i] == value) {
result = false;
}
}
add = 0;
value = value.replace("-","");
value = value.replace(/\./g,"");
for( var j=0; j < 9; j++ ) {
add += parseInt(value.charAt(j),10) * (10-j);
}
rev = 11 - ( add % 11 );
if( rev == 10 || rev == 11) {
rev = 0;
}
if( rev != parseInt(value.charAt(9),10) ) {
result = false;
}
add = 0;
for( var k=0; k < 10; k++ ) {
add += parseInt(value.charAt(k),10) * (11-k);
}
rev = 11 - ( add % 11 );
if( rev == 10 || rev == 11) {
rev = 0;
}
if( rev != parseInt(value.charAt(10),10) ) {
result = false;
}
if ( result ) {
input.parentNode.previousSibling.previousSibling.classList.remove('hide');
input.parentNode.nextSibling.nextSibling.classList.add('hide');
input.classList.remove('form_invalido');
input.classList.add('form_valido');
} else {
input.parentNode.previousSibling.previousSibling.classList.add('hide');
input.parentNode.nextSibling.nextSibling.classList.remove('hide');
input.classList.add('form_invalido');
input.classList.remove('form_valido');
}
}