nullifying function action if result is false

Asked

Viewed 48 times

2

I have the following function: if the input is Nan, it focuses on the field and changes the border

function validaNumero(){
	dado = document.getElementById("new_partner");
	var formulario = document.getElementById("new_partner");
	var dado = formulario.partner_registry_number.value;
		if(isNaN(dado)) {
			formulario.partner_registry_number.style.focus;
			formulario.partner_registry_number.style.border = "2px solid red";
			return false;
		} 
	}

So far, so good, but after the first time the function is accessed, the bar always turns red, even typing a valid data. How to solve this?

  • You can put the HTML?

  • I believe I will have to call the function again at some point (onchange, Submit) and if it is valid to return the edge to normal.

  • Click on [Edit] and join the HTML so we can answer your question.

1 answer

2

Every time the code is executed and the value is Nan, it will change the border to red. After the value is no longer Nan, you need to get the border back to its original state.

You only need one else.

if(isNaN(dado)) {
    formulario.partner_registry_number.style.border = "2px solid red";
} else {
    formulario.partner_registry_number.style.border = ""; // borda original
}

Or to optimize the code..

formulario.partner_registry_number.style.border = isNaN(dado) ? '2px solid red' : '';
  • formulario.partner_registry_number.style.border = isNaN(dado) ? "2px solid red" : ""; to stay in one line. +1

  • I put in the answer, @Sergio.

Browser other questions tagged

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