Good morning! I've been thinking for a few hours and I don't know where the error is, I have to validate that a name does not contain spaces!
function validarNombre(){
var p1 = document.getElementById("nombre").value; //tomamos en una variable lo ingresado en el login nombre
var espacios = false;
var cont = 0;
while (!espacios && (cont < p1.length)) {
if (p1.charAt(cont) == " "){
espacios = true;
cont++;
}
}
if (espacios) {
alert ("La contraseña no puede contener espacios en blanco");
return false;
}
}
<div class="container">
<center><p class="usuario">Usuarios </p></center>
<div class="login">
<form name="login" method="post" action="#">
<label for="nombre">Nombre:</label><br>
<input type="text" onSubmit="return validarNombre()" id="nombre" name="nombre" value=""><br>
<label for="correo">Email:</label><br>
<input type="correo" name="correo" value=""><br>
<a href="#"> Suscribite Ahora </a>
<p class="submit" onclick="" >
<input type="submit" name="commit" value="Login"></p>
</form>
</div>
</div>
Thank you very much in advance!
Hello, your code is not efficient when checking character by character if it has spaces or not, you can use regex or regular expression, like this to check it:
As mentioned in the comments, the code above matches spaces, tabs, and so on. If you are only looking for space, do it in the form
You don't need to reinvent the wheel, if you want to check if a character exists or not within a string use the function
.indexOf()
.If the result is -1 it indicates that the string passed as parameter (in your case " ") was not found in the original string. Otherwise it returns the position where the first occurrence was found.
Example
In your case the code can be like this
you have an infinite loop
It should be
I answer this so that you get out of the question about why it does not work. However, Wilfredo's answer is the correct way to do this check . He learns regular expressions, they will simplify your life. Though...
Something simpler and without using regex, is to do a split and count the number of values that are found, and based on that you will know if there are spaces or not.
I admit that it is not a great solution, but it is something basic and quick to program.
Example:
Also, what you can do is use
indexOf()
(as mentioned in a previous comment).Example: