It’s a very unusual thing but…
Intent to change a class of an element when its value matches with a rule by keyup/onchange/input event (all of these already tried).
Have this
$(document).ready(function() {
$('#cpf').on('keyup', function() {
var element = $('#cpf');
var val = element.val();
let cpfValue = val.replace(/D/g, "");
var result = validateCpf(cpfValue);
console.log('RESULT: ', result);
if (result==1) {
$('#cpf').addClass('is-valid');
} else {
$('#cpf').addClass('is-invalid');
}
});
//validateCpf(string)
function validateCpf(param) {
var strToMatch = param;
let total = 0;
let factor;
let x;
function gear(str, flag) {
if (!flag) {
var substr = str.substring(0, 9);
x = valDig(substr);
console.log('match?: ', x == strToMatch.substr(9, 1))
if (x == strToMatch.substr(9, 1)) {
var substr = str.substring(0, 9) + str.substr(9, 1);
gear(substr, true);
} else {
return false;
}
} else {
var substr = str;
x = valDig(substr, true);
console.log('match2? :', x == strToMatch.substr(10, 1));
if (x == strToMatch.substr(10, 1)) {
console.log('It worked!');
return 1;
} else {
console.log('no valid');
return false;
}
}
function valDig(str, flag) {
flag ?
factor = 11 :
factor = 10;
total = 0;
minhaString = str;
for (let i = 0; i < minhaString.length; i++) {
total += parseInt(minhaString.charAt(i)) * factor;
factor--;
}
var rest = total % 11;
if (rest == 10) {
x = 0;
} else {
x = Math.abs(11 - rest);
}
return x;
}
}
console.log(param.length);
if (param.length == 11) {
gear(param)
} else {
return false;
}
}
})
<input id="cpf" class="form-control @error('cpf') is-invalid @enderror" type="text"
name="cpf" value="@error('cpf') {{''}} @else {{ old('cpf') }} @enderror"
placeholder="@error('cpf') Insira um número de CPF válido. @enderror" />
The validating itself is already done, but the function, curiosly, returns ‘undefined’ when it matches, while ‘false’ when it doesn’t, as you can see from the console logs below:
8
(índice):96 RESULT: false
(índice):153 9
(índice):96 RESULT: false
(índice):153 10
(índice):96 RESULT: false
(índice):153 11
(índice):114 match?: true
(índice):124 match2? : true
(índice):126 It worked!
(índice):96 RESULT: undefined
The last occurence refers to the console.log('match?: ', x == strToMatch.substr(9, 1))
, which is just executed when length of the string matches 11 (once it’s a dinamic change).
Any helps will be well come.