3
Good afternoon! I am trying to validate a form by "Onchange" with javascript, the script worked correctly but is presenting the following error:
When I try to fill in any form field without having filled in the previous fields it returns to the first field.
I’m a beginner in javascript, how can I solve this?
The form with the script is here: http://jsbin.com/tumasupika/1/edit?html,css,js,output
Validation script:
function val(){
var campo = document.getElementsByClassName('valida');
var alerta = document.getElementsByClassName('alerta');
//exucuta o laço
for(i=0;i<campo.length;i++){
var tipo = campo.item(i).getAttribute('data-type');
if(tipo == "text" || tipo == "number" || tipo == "select"){
if(campo.item(i).value === "" || campo.item(i).value.length < 8){
alerta.item(i).setAttribute('style', 'background-position:-525px');
campo.item(i).setAttribute('style', 'background-color:#fff;border:1px solid #f00');
campo.item(i).focus();
return false;
break;}
alerta.item(i).removeAttribute('style');
campo.item(i).setAttribute('style', 'background-color:#fff');
}
else if(tipo == "email"){
if(campo.item(i).value.length < 10 || campo.item(i).value.indexOf('@')==-1 || campo.item(i).value.indexOf('.')==-1 || campo.item(i).value.indexOf('.com')==-1){
alerta.item(i).setAttribute('style', 'background-position:-525px');
campo.item(i).setAttribute('style', 'background-color:#fff;border:1px solid #f00');
campo.item(i).focus();
return false;
break;}
alerta.item(i).removeAttribute('style');
campo.item(i).setAttribute('style', 'background-color:#fff');
}
}
}
Got it @Maicon Carraro, thank you very much, but I wanted to validate each field individually.
– Odair
To validate each field individually, you will need to check them by
id
orname
.– Eduardo Silva
Thank you @Eduardosilva
– Odair
@Odair I updated my answer with individual validation, take a look.
– Maicon Carraro
@Maiconcarraro Thank you very much!
– Odair
@Odair I made a new suggestion for your function to validate all :)
– Maicon Carraro
Thank you @Maiconcarraro, it worked perfectly, thanks for the help :)
– Odair