Reputation: 154
I'm trying to validate my login form so that the field will have a min/max length before the values being posted to my PHP file.
JavaScript:
function loginValidation() {
var user = document.login.username.value;
var pass = document.login.password.value;
if (user.length <= 6 || user.length > 20) {
alert("Please make sure the username is between 7 and 20 characters.");
return false;
}
if (pass.length <= 8 || pass.length > 50) {
alert("Please make sure the password field is between 9 and 50 characters.");
return false;
}
}
HTML:
<form name="login" onsubmit="loginValidation()" action="login.php" method="post">
<div class="form-group row">
<label for="username" class="lead para col-sm-4">Username</label>
<input type="text" class="form-control transparent col-sm" id="username" name="username" placeholder="Username">
</div>
<div class="form-group row">
<label for="password" class="lead para col-sm-4">Password</label>
<input type="password" class="form-control col-sm" id="password" name="password" placeholder="Password">
</div>
<button type="submit" class="btn btn-outline-primary">LOGIN</button>
</form>
It seems that the code is ignoring the Function or that it just doesn't work (errors maybe?).
Other information that might be useful to know is that the JavaScript file with all my functions is external.
<script src="/JS/functions.js"></script>
Upvotes: 1
Views: 64
Reputation: 67505
You are just missing the return
in the function call in your onsubmit
, should be like :
<form name="login" onsubmit="return loginValidation()" action="login.php" method="post">
_____________________________^^^^^^
It will be better to attach the event in your JS part :
document.querySelector('form[name="login"]').addEventListener("submit", loginValidation);
function loginValidation() {
var user = document.login.username.value;
var pass = document.login.password.value;
if (user.length <= 6 || user.length > 20) {
alert("Please make sure the username is between 7 and 20 characters.");
return false;
}
if (pass.length <= 8 || pass.length > 50) {
alert("Please make sure the password field is between 9 and 50 characters.");
return false;
}
return true;
}
<form name="login" onsubmit="return loginValidation()" action="login.php" method="post">
<div class="form-group row">
<label for="username" class="lead para col-sm-4">Username</label>
<input type="text" class="form-control transparent col-sm" id="username" name="username" placeholder="Username">
</div>
<div class="form-group row">
<label for="password" class="lead para col-sm-4">Password</label>
<input type="password" class="form-control col-sm" id="password" name="password" placeholder="Password">
</div>
<button type="submit" class="btn btn-outline-primary">LOGIN</button>
</form>
Upvotes: 2