I am a novice in JavaScript and I have a question. Maybe he has already been answered, but I could not find the answer (links to the answer are welcome!). I have made a small form that checks whether everything has been filled in correctly. I use the "if / else" statement in my code to check the input. In the cosole.log he returns 'true' while he has to return 'false' because I have not entered anything in the input boxes. I want my "else" statement to return "true" only when everything is filled in correctly.
Thank you in advance.
validation.js
function validate() {
var fields = f1.getElementsByTagName('input');
var attribute = [];
for (i = 0; i < fields.length; i++) {
if (fields[i].type != "submit") {
attribute.push(fields[i].getAttribute('validate').split('|'));
}
}
var name = document.f1.name.value;
var namelength = document.f1.name.value.length;
var status = false;
var emptyName = attribute[0][0];
////////////////////////////////////////////////////////////////
// CHECK NAME
////////////////////////////////////////////////////////////////
if (emptyName == "empty-allowd") {
emptyName = 0;
}
if (emptyName == "empty-not-allowd") {
emptyName = 1;
}
if (emptyName == 0) {
document.getElementById("namelocation").innerHTML = "ok";
status = true;
}
if (emptyName == 1) {
document.getElementById("namelocation").innerHTML = "Required.";
status = false;
}
if (namelength > 0 && namelength < attribute[0][1]) {
document.getElementById("namelocation").innerHTML = "Name not shorter than" + " " + attribute[0][1] + " " + "characters.";
status = false;
}
if (namelength > attribute[0][2]) {
document.getElementById("namelocation").innerHTML = "Name not longer than" + " " + attribute[0][2] + " " + "characters.";
status = false;
} else {
status = true;
console.log(status);
alert(status);
}
return status;
}
form.html
<form name="f1" action="" method="/" onsubmit="return validate()">
<table>
<tr>
<td>Name:</td>
<td>
<input type="text" id="name" name="name" validate="empty-not-allowd|5|20" />
<span id="namelocation" style="color:red"></span>
</td>
</tr>
<tr>
<td colspan="2">
<input type="submit" value="register" /> </td>
</tr>
</table>
</form>
Aucun commentaire:
Enregistrer un commentaire