Prevent user to change field before completing

Asked

Viewed 66 times

0

In some specific forms, I want to validate if user has completed the field in full.

Should he come out of input, an alert on the screen is displayed, and then the focus goes back to that field.

I tried to do that with the Javascript down, but it didn’t work out like I want.

<script type="text/javascript">
function validaHora(x){
	if (x.value.length(5)){
		alert ("ERRO!");
		x.focus();
		return false;
	}else{
		alert ("OK!");
		return true;
	}
}
</script>

in the input

@onblur = "return ValidaHora(this)"
  • What is the criterion of "fully fulfilling"?

2 answers

3


I see some problems in your code. First the name of the function called in onblur is different from the function name:

@onblur = "return ValidaHora(this)" <-- "V" maiúsculo
                  ↑
function validaHora(x){             <-- "v" minúsculo
         ↑

If it was not a typo of the question, only then would it make an error of non-existent function and the code wouldn’t work.

But if it was just a typo of the question and the names are the same in the code, it would give error in the x.value.length(5): the .length is not a function, therefore has no () after, it would just be x.value.length.

Another problem is the use of alert with .focus(), because this will catch the page by firing the alert and endlessly, because when the if is satisfied, the field will gain focus and by clicking to close the alert, the field will lose focus by calling again the function and entering again the if, creating an infinite loop where the alert box will be displayed continuously, locking the tab.

One way to avoid this, in addition to the aforementioned corrections, is to create a flag (control variable) to prevent the alert is fired again when closing it:

var alerta; // flag
function ValidaHora(x){
   if (x.value.length < 5){
      if(!alerta){
         alerta = true;
         alert("ERRO!");
         setTimeout(function(){
            x.focus();
            alerta = false;
         }, 1);
      }
      return false;
   }else{
      alert("OK!");
      return true;
   }
}
Mínimo 5 caracteres:<br>
<input onblur="return ValidaHora(this)">

2

Here’s a simple option, if the guy clicks input and then click cora and the input is invalid he gives a alert. Kind in the .blur of input you make a if .is(":invalid") and whether or not the alert.

inserir a descrição da imagem aqui

Follow the image code above

$('input').blur(function (el) {
	if ($(el.target).is(":invalid")) {
                this.focus();
		console.log('pelo menos 10 letras');
	}
});
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>

<input id="" type="text" minlength="10" required>
<input id="" type="text" minlength="10" required>
<input id="" type="text" minlength="10" required>

Browser other questions tagged

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