DarkFenix
DarkFenix

Reputation: 746

Return false does not work in my javascript function

I'm new to javascript, I try to validate my form inside the onSubmit using javascript but it does not work, as if it will not enter my last if where I compare the size of a string. Always returns true and ends sending the form thus present input problems

function validaDatos(form){
	var mensaje="";
	var solonumeros = /^([0-9])*$/
	var sololetras = /^([A-Z]|[a-z])*$/
	var doc = form.doc.value;
	var apepa = form.apepa.value;
	var apema = form.apema.value;
	var nombre = form.nombre.value;
	var telefono = form.telefono.value;
	var usuario = form.usuario.value;

	if(!solonumeros.test(doc)){
		mensaje+="Campo Documento erróneo, solo se aceptan Números";
	}
	if(!sololetras.test(apepa)){
		mensaje+="Campo Apellido Paterno erróneo, solo se aceptan Letras";
	}
	if(!sololetras.test(apema)){
		mensaje+="Campo Apellido Materno erróneo, solo se aceptan Letras";
	}
	if(!sololetras.test(nombre)){
		mensaje+="Campo Nombre erróneo, solo se aceptan Letras <br>";
	}
	if(!solonumeros.test(telefono)){
		mensaje+="Campo Teléfono, solo se aceptan Números ";
	}
	if(!solonumeros.test(usuario) && !sololetras.test(usuario)){
		mensaje+="Campo Usuario , Solo se Acepta Números y Letras";
	}
	alert(mensaje.length); //return > 0
    /* No compare , no return false */
	if(mensaje.length !=0){
		document.getElementByClassName('msgerror').innerHTML  = mensaje;
		return false;
	}
	
}
<form action="Models/clsUsuario.php" method="POST" accept-charset="utf-8" id="frmRegistro" onsubmit="return validaDatos(this);">
<label for="">Documento </label>
<input type="text" id="doc" name="doc" required  maxlength="11">
<label for="">Apellido P.</label>
<input type="text" id="apepa" name="apepa" required  maxlength="80">
<label for="">Apellido M.</label>
<input type="text" id="apema" name="apema" required  maxlength="80">
<label for="">Nombres </label>
<input type="text" id="nombre" name="nombre" required  maxlength="80">
<label for="">Email : </label>
<input type="email" id="email" name="email" required>
<label for="">Teléfono : </label>
<input type="tel" id="telefono" name="telefono"  required>
<label for="">Usuario  </label>
<input type="text" id="usuario" name="usuario" required>
<label for="">Clave  </label>
<input type="password" id="clave" name="clave" required>

<label for="">Dirección : </label>
<textarea name="direccion" id="direccion" required></textarea>

<input type="hidden" name="registrar" value="registrar">
<input type="submit" name="registrar" value="Registro" >
<span class="msgerror"></span>
				
</form>

Sorry if my programming language (variables and messages) is not English. Before the if, I show the length of the message variable, but I should enter the if more it does not.

Code Run

Upvotes: 1

Views: 1583

Answers (3)

some
some

Reputation: 49582

Your error is in this part:

if(mensaje.length !=0){
    document.getElementByClassName('msgerror').innerHTML  = mensaje;
    return false;
}

There is no function called getElementByClassName. There is a function called getElementsByClassName (Notice the missing s in getElementsByClassName and that it will always return an array: It there is no elements that match, the array will be empty)

In Chrome you can check the Preseve Log in the developers tools to make the browser keep the logs between page loads.

The reason you don't see anything right now is that the error causes the function to abort, and since the form doesn't return false, the form will be submitted.

I also noticed that you set several different error messages by concatenating strings. That will get you into trouble if there are multiple errors, for example you could get "Campo Documento erróneo, solo se aceptan NúmerosCampo Apellido Paterno erróneo, solo se aceptan Letras" (Notice a missing separator between NúmerosCampo). I suggest using an array instead, and then join it with a separator when you use it.

function validaDatos(form){
  var mensaje=[];

  // get the element where to set errors. It would be better to use
  // getElementById, but if you don't have an id on the element, that will
  // obviously not work. 
  var errorElement = document.getElementsByClassName("msgerror")[0];
  var solonumeros = /^([0-9])*$/
  var sololetras = /^([A-Z]|[a-z])*$/
  var doc = form.doc.value;
  var apepa = form.apepa.value;
  var apema = form.apema.value;
  var nombre = form.nombre.value;
  var telefono = form.telefono.value;
  var usuario = form.usuario.value;

  if(!solonumeros.test(doc)){
    mensaje.push("Campo Documento erróneo, solo se aceptan Números");
  }
  if(!sololetras.test(apepa)){
    mensaje.push("Campo Apellido Paterno erróneo, solo se aceptan Letras");
  }
  if(!sololetras.test(apema)){
    mensaje.push("Campo Apellido Materno erróneo, solo se aceptan Letras");
  }
  if(!sololetras.test(nombre)){
    mensaje.push("Campo Nombre erróneo, solo se aceptan Letras");
  }
  if(!solonumeros.test(telefono)){
    mensaje.push("Campo Teléfono, solo se aceptan Números");
  }
  if(!solonumeros.test(usuario) && !sololetras.test(usuario)){
    mensaje.push("Campo Usuario , Solo se Acepta Números y Letras");
  }
  console.log(mensaje.length); //return > 0
    /* No compare , no return false */

  // test if there is an error (the length is not null) and if the
  // errorElement exists.
  if(mensaje.length && errorElement){
    errorElement.innerHTML = mensaje.join("<br>");
  }

  // returns true if the length is 0, or false if it is any other value.
  return mensaje.length === 0;
}

Upvotes: 1

iwaduarte
iwaduarte

Reputation: 1700

Try to use like that:

if(mensaje.length !==0){ //two equals sign
    document.getElementByClassName('msgerror').innerHTML  = mensaje;
    return false;
}

Also you can check if a string is empty, null or undefined use the function below:

function isEmpty(str) {
    return (!str || 0 === str.length);
}

To understand the difference between = vs == :

Features of comparisons:

Two strings are strictly equal when they have the same sequence of characters, same length, and same characters in corresponding positions. Two numbers are strictly equal when they are numerically equal (have the same number value). NaN is not equal to anything, including NaN. Positive and negative zeros are equal to one another. Two Boolean operands are strictly equal if both are true or both are false. Two distinct objects are never equal for either strict or abstract comparisons. An expression comparing Objects is only true if the operands reference the same Object. Null and Undefined Types are strictly equal to themselves and abstractly equal > to each other.

Comparison operator

*********** UPDATE ************* Try to check the lines below. Insert into the if:

console.log ("success") //this line
document.getElementByClassName('msgerror')[0].innerHTML  = mensaje;

You have to check if you have an element with this 'msgerror' class.

Upvotes: 0

Alexandre Cristo
Alexandre Cristo

Reputation: 331

You have to return something out of the if statement.

Try this:

function validaDatos(form){
var mensaje="";
var solonumeros = /^([0-9])*$/
var sololetras = /^([A-Z]|[a-z])*$/
var doc = form.doc.value;
var apepa = form.apepa.value;
var apema = form.apema.value;
var nombre = form.nombre.value;
var telefono = form.telefono.value;
var usuario = form.usuario.value;

if(!solonumeros.test(doc)){
    mensaje+="Campo Documento erróneo, solo se aceptan Números";
}
if(!sololetras.test(apepa)){
    mensaje+="Campo Apellido Paterno erróneo, solo se aceptan Letras";
}
if(!sololetras.test(apema)){
    mensaje+="Campo Apellido Materno erróneo, solo se aceptan Letras";
}
if(!sololetras.test(nombre)){
    mensaje+="Campo Nombre erróneo, solo se aceptan Letras <br>";
}
if(!solonumeros.test(telefono)){
    mensaje+="Campo Teléfono, solo se aceptan Números ";
}
if(!solonumeros.test(usuario) && !sololetras.test(usuario)){
    mensaje+="Campo Usuario , Solo se Acepta Números y Letras";
}

/* No compare , no return false */
if(mensaje.length !=0){
    document.getElementByClassName('msgerror').innerHTML  = mensaje;
    return false;
}
return true;

}

Upvotes: 0

Related Questions