Back Focus to a field after validation

Asked

Viewed 155 times

1

good afternoon!

I’d like to help on a little something here, I have a name field from the card and I’d like to validate it to see if it’s empty, made and works only that the time I click on the message that Alert sent it does not return the focus to the input but keeps giving the message as if it was in an infinite loop. Can anyone help me!!

Follows Code.....

JS

function validanome(){
    if (document.getElementById("nomecartao").value == ""){
        alert("Por Favor Insira o Nome do Titular!!!");
        document.getElementById("nomecartao").focus();
    }
}

HTML

<input type="text" class="nomecartao" name="nomecartao" id="nomecartao" maxlength="100" onblur="validanome()" onkeyup="mostrar()">
  • Your second question is duplicate and avoid two questions in the same post https://answall.com/questions/106728/como-n%C3%A3o-allow-n%C3%Bameros-numa-textbox

1 answer

1

The problem with your code is in onblur and when clicked it stays "in Blur" and enters a looping just you change to onChange.

Use the onblur for validation of a field is very bad and causes a lot of problems. If the user decides to browse, it simply cannot. When they leave the camp, they are forced to return. The most correct would be to do a validation after the user submits the form and then yes perform the validation in the client-side

function validanome(){
    if (document.getElementById("nomecartao").value == ""){
        alert("Por Favor Insira o Nome do Titular!!!");
        var nome = document.getElementById("nomecartao");
    }
}
<input type="text" class="nomecartao" name="nomecartao" id="nomecartao" maxlength="100" onchange="validanome()" onkeyup="mostrar()">

  • Giovani thank you very much, but I need the event onblur because this is a text box and I need that as soon as the focus leaves it I need to call the validation

  • @Joãobardella I explained why onblur is a problem and replaces onclick with onchange that might meet your need

  • Because this is for a payment system that I am doing as the user is typing the data already appear on the credit card next understood, so there is no button submit

Browser other questions tagged

You are not signed in. Login or sign up in order to post.