I'm currently writing a registration form in HTML and have come across a couple of problems. Firstly, I have to have a separate button outside of the form tags to run the function as my submit button just submits the form whether input fields are entered incorrectly, only showing the validation alerts for a split second. Secondly, if I enter the email correctly it states that 'email.includes' is not valid, however, it still runs as it should, this error does not appear if I enter an invalid email. Thanks for any answers (I know my code is not great, I'm still learning a lot)
function validate_form() {
var forename = document.getElementById("forename");
var surname = document.getElementById("surname");
var username = document.getElementById("username");
var password = document.getElementById("password");
var re_password = document.getElementById("re_password");
var email = document.getElementById("email");
var errors = 0
var special_chars = "<>#!#$%^&*()_+[]{}?:;|'\"\\,./~`-=";
if (forename.value == "") {
//document.getElementById("forename").style.background = "red";
forename_confirmation.style.visibility = 'visible';
var errors = errors + 1
} else
for (var i = 0; i < forename.value.length; i++) {
if (special_chars.indexOf(forename.value.charAt(i)) != -1) {
forename_chars.style.visibility = 'visible'
}
}
if (surname.value == "") {
//document.getElementById("surname").style.background = "red";
surname_confirmation.style.visibility = 'visible';
var errors = errors + 1
} else
for (var i = 0; i < surname.value.length; i++) {
if (special_chars.indexOf(surname.value.charAt(i)) != -1) {
surname_chars.style.visibility = 'visible'
}
}
if (username.value == "") {
//document.getElementById("username").style.background = "red";
username_confirmation.style.visibility = 'visible';
var errors = errors + 1
} else
for (var i = 0; i < username.value.length; i++) {
if (special_chars.indexOf(username.value.charAt(i)) != -1) {
username_chars.style.visibility = 'visible'
}
}
if (password.value == "") {
//document.getElementById("password").style.background = "red";
pass_confirmation.style.visibility = 'visible';
var errors = errors + 1
}
if (password.value != re_password.value) {
//document.getElementById("re_password").style.background = "red";
repass_confirmation.style.visibility = 'visible';
var errors = errors + 1
}
if (email.value == "") {
//document.getElementById("email").style.background = "red";
var errors = errors + 1
}
if (errors != "0") {
alert("Whoops! Looks like you didn't enter your details properly")
}
if (!email.value.includes("#") || !email.includes(".")) {
//document.getElementById("email").style.background = "blue";
email_confirmation.style.visibility = 'visible';
return false;
}
return (true);
}
<!DOCTYPE html>
<html>
<head>
<title>Login form</title>
<link rel="stylesheet" type="text/css" href="Login Form CSS.css">
<script src="Registration function.js" defer></script>
<body>
<div class="loginbox">
<img src="Logo.jpg" class="avatar">
<h1> Create Account </h1>
<form name="login-form">
<div id="forename_confirmation"> Please fill in this box </div>
<div id="forename_chars"> Don't use special characters</div>
<p>Forename
<p>
<input type="text" name="forename" id="forename" placeholder="Enter Forename here">
<div id="surname_confirmation"> Please fill in this box </div>
<div id="surname_chars"> Don't use special characters</div>
<p>Surname
<p>
<input type="text" name="surname" id="surname" placeholder="Enter Surname here">
<div id="username_confirmation"> Please fill in this box </div>
<div id="username_chars"> Don't use special characters</div>
<p>Username
<p>
<input type="text" name="username" id="username" placeholder="Enter Username here">
<div id="pass_confirmation"> Please fill in this box </div>
<div id="pass_chars">Don't use special characters</div>
<p>Password
<p>
<input type="password" name="password" id="password" placeholder="Enter Password here">
<div id="repass_confirmation"> Passwords do not match </div>
<p>Re-enter Password
<p>
<input type="password" name="re_password" id="re_password" placeholder="Re-enter your password here">
<div id="email_confirmation"> Please enter a valid email </div>
<p>Email
<p>
<input type="email" name="email" id="email" placeholder="Enter Email here">
<!--
<p>Gender<p>
<input type="radio" id="Male" name="Gender" value="Male">Male</input>
<input type="radio" id="Female" name="Gender" value="Female">Female</input>
-->
<button onclick="validate_form()" type="Submit" value="True" name="button-submit"> Submit </button>
<br />
<br />
Forgot your password?
<br />
Already got an account?
<br /><br />
</form>
<!-- <button onclick="validate_form()" type="submit"> Validate </button> -->
</div>
</body>
</head>
<script>
forename_confirmation.style.visibility = 'hidden'
forename_chars.style.visibility = 'hidden'
surname_confirmation.style.visibility = 'hidden'
surname_chars.style.visibility = 'hidden'
username_confirmation.style.visibility = 'hidden'
username_chars.style.visibility = 'hidden'
pass_confirmation.style.visibility = 'hidden'
pass_chars.style.visibility = 'hidden'
repass_confirmation.style.visibility = 'hidden'
email_confirmation.style.visibility = 'hidden'
</script>
</body>
</html>
Two issues here:
When you don't want to submit your form (e. g. entered details are incorrect), you will need to prevent it from submitting. In JavaScript, you can to this with preventDefault().
So achieve this, I added the line event.preventDefault() to your if statement that checks if there are any errors. Keep in mind that you need to pass the event parameter to your function in order to get preventDefault() working.
Secondly, you need to check if the value of your email field includes something.
You got your email field like this: var email = document.getElementById('email');, so you need to check the value like this: email.value.includes('bla').
All together, your script works perfectly fine:
function validate_form(event) {
var forename = document.getElementById("forename");
var surname = document.getElementById("surname");
var username = document.getElementById("username");
var password = document.getElementById("password");
var re_password = document.getElementById("re_password");
var email = document.getElementById("email");
var errors = 0
var special_chars = "<>#!#$%^&*()_+[]{}?:;|'\"\\,./~`-=";
if (forename.value == "") {
//document.getElementById("forename").style.background = "red";
forename_confirmation.style.visibility = 'visible';
var errors = errors + 1
} else
for (var i = 0; i < forename.value.length; i++) {
if (special_chars.indexOf(forename.value.charAt(i)) != -1) {
forename_chars.style.visibility = 'visible'
}
}
if (surname.value == "") {
//document.getElementById("surname").style.background = "red";
surname_confirmation.style.visibility = 'visible';
var errors = errors + 1
} else
for (var i = 0; i < surname.value.length; i++) {
if (special_chars.indexOf(surname.value.charAt(i)) != -1) {
surname_chars.style.visibility = 'visible'
}
}
if (username.value == "") {
//document.getElementById("username").style.background = "red";
username_confirmation.style.visibility = 'visible';
var errors = errors + 1
} else
for (var i = 0; i < username.value.length; i++) {
if (special_chars.indexOf(username.value.charAt(i)) != -1) {
username_chars.style.visibility = 'visible'
}
}
if (password.value == "") {
//document.getElementById("password").style.background = "red";
pass_confirmation.style.visibility = 'visible';
var errors = errors + 1
}
if (password.value != re_password.value) {
//document.getElementById("re_password").style.background = "red";
repass_confirmation.style.visibility = 'visible';
var errors = errors + 1
}
if (email.value == "") {
//document.getElementById("email").style.background = "red";
var errors = errors + 1
}
if (errors != "0") {
alert("Whoops! Looks like you didn't enter your details properly");
event.preventDefault(); // Prevent the form from submitting
}
if (!email.value.includes("#") || !email.value.includes(".")) {
//document.getElementById("email").style.background = "blue";
email_confirmation.style.visibility = 'visible';
return false;
}
return (true);
}
<!DOCTYPE html>
<html>
<head>
<title>Login form</title>
<link rel="stylesheet" type="text/css" href="Login Form CSS.css">
<script src="Registration function.js" defer></script>
<body>
<div class="loginbox">
<img src="Logo.jpg" class="avatar">
<h1> Create Account </h1>
<form name="login-form">
<div id="forename_confirmation"> Please fill in this box </div>
<div id="forename_chars"> Don't use special characters</div>
<p>Forename
<p>
<input type="text" name="forename" id="forename" placeholder="Enter Forename here">
<div id="surname_confirmation"> Please fill in this box </div>
<div id="surname_chars"> Don't use special characters</div>
<p>Surname
<p>
<input type="text" name="surname" id="surname" placeholder="Enter Surname here">
<div id="username_confirmation"> Please fill in this box </div>
<div id="username_chars"> Don't use special characters</div>
<p>Username
<p>
<input type="text" name="username" id="username" placeholder="Enter Username here">
<div id="pass_confirmation"> Please fill in this box </div>
<div id="pass_chars">Don't use special characters</div>
<p>Password
<p>
<input type="password" name="password" id="password" placeholder="Enter Password here">
<div id="repass_confirmation"> Passwords do not match </div>
<p>Re-enter Password
<p>
<input type="password" name="re_password" id="re_password" placeholder="Re-enter your password here">
<div id="email_confirmation"> Please enter a valid email </div>
<p>Email
<p>
<input type="email" name="email" id="email" placeholder="Enter Email here">
<!--
<p>Gender<p>
<input type="radio" id="Male" name="Gender" value="Male">Male</input>
<input type="radio" id="Female" name="Gender" value="Female">Female</input>
-->
<button onclick="validate_form(event)" type="Submit" value="True" name="button-submit"> Submit </button>
<br />
<br />
Forgot your password?
<br />
Already got an account?
<br /><br />
</form>
<!-- <button onclick="validate_form()" type="submit"> Validate </button> -->
</div>
</body>
</head>
<script>
forename_confirmation.style.visibility = 'hidden'
forename_chars.style.visibility = 'hidden'
surname_confirmation.style.visibility = 'hidden'
surname_chars.style.visibility = 'hidden'
username_confirmation.style.visibility = 'hidden'
username_chars.style.visibility = 'hidden'
pass_confirmation.style.visibility = 'hidden'
pass_chars.style.visibility = 'hidden'
repass_confirmation.style.visibility = 'hidden'
email_confirmation.style.visibility = 'hidden'
</script>
</body>
</html>
If there is an validation error you need to prevent the event default behavior in order to prevent the browser from redirecting to target page (what you specified in the action attribute, or reloading the current page if not specified):
https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault
Your second question: I guess its email.value.includes (as you already used in your code on an other point) and you whant to check the value not the HTML-Node itself.
You might also want to look in email regex validation which would match the requirements of an email validation way better than checking for "#" an "." e.g. https://www.w3resource.com/javascript/form/email-validation.php
Related
This is a two-part question.
Part 1. The passConfirm function that I currently have is there to make sure that the password and confirming password values match. Right now, when I type in my password the button disappears. The purpose of this function is to display a message while the user is creating a password and confirming it, that the password does or does not match. Does anyone know why that is happening based on the code I have?
Part 2. Is there a way to refactor my passConfirm function? I tried doing it by adding it to the validateForm function (Please see commented code for my example). It wasn't working tho.
function printError(elemId, message) {
document.getElementById(elemId).innerHTML = message;
}
function validateForm() {
event.preventDefault();
var name = document.regForm.FullName.value;
var email = document.regForm.email.value;
var phone = document.regForm.phone.value;
var password = document.regForm.Password.value;
var confirmPassword = document.regForm.ConfirmPassword.value;
const phoneno = /^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/;
var nameError = emailError = phoneError = passwordError = true;
//Empty name input error message
if (name == "") {
printError("nameError", "Please enter your name")
}
//Empty email input error message
if (email == "") {
printError("emailError", "Please enter a valid email")
}
//Empty phone input error message
if (phone == "") {
printError("phoneError", "Please enter your phone numnber")
}
//Non valid phone number error messsage
if (phone.match(phoneno)) {
return true;
} else {
printError("phoneError", "Please enter a valid phone number")
}
//Empty Password input
if (password == "") {
printError("passwordError", "Please enter a password")
}
//Empty Cofirm Password input
if (confirmPassword == "") {
printError("confirmpassError", "Please confirm your password")
}
//I tried refactoring the passConfirm function and additing it here.
//if (password.match(confirmPassword)) {
// printPass("matchingPassword", "Passwords match")
// document.getElementById("matchingPassword").style.color = "green";
//} else {
// printPass("matchingPassword", "Passwords do no match")
// document.getElementById("matchingPassword").style.color = "red";
//}
};
var passConfirm = function() {
if (document.getElementById("Password").value == document.getElementById("ConfirmPassword").value) {
document.getElementById("matchingPassword").style.color = "green";
document.getElementById("matchingPassword").style.fontWeight = "Heavy";
document.getElementById("matchingPassword").innerHTML = "Passwords match!"
} else {
document.getElementById("matchingPassword").style.color = "red";
document.getElementById("matchingPassword").style.fontWeight = "Heavy";
document.getElementById("matchingPassword").innerHTML = "Passwords do NOT match!"
}
}
fieldset {
width: 420px;
height: 950px;
}
<h1>Hello, please register!</h1>
<div class="container">
<form name="regForm" class="form" onsubmit="return validateForm(event)">
<fieldset>
<div class="row">
<label>Full Name</label></br>
<input name="FullName" type="text" placeholder="John Doe" id="FullName" />
<span class="error" id="nameError"></span>
</div>
<div class="row">
<label>Email</label></br>
<input name="email" type="email" placeholder="johndoe#email.com" id="Email" />
<span class="error" id="emailError"></span>
</div>
<div class="row">
<label>Phone Number</label></br>
<input name="phone" type="tel" placeholder="(123) 456-7890" id="PhoneNumber" />
<span class="error" id="phoneError"></span>
</div>
<div class="row">
<label>Password</label></br>
<input name="Password" id="Password" type="Password" placeholder="Password" onchange='passConfirm();' />
<span class="error" id="passwordError"></span>
</div>
<div class="row">
<label>Confirm Password</label></br>
<input name="ConfirmPassword" id="ConfirmPassword" type="Password" placeholder="Confirm Password" onchange='passConfirm();' />
<span class="error" id="confirmpassError"></span>
</div>
<span id="matchingPassword">
<button type="submit" value="submit">Sign Me Up!</button>
</fieldset>
</form>
</div>
Your button disappears because you use InnerHTML method to display the message, which overrides it. Though your logic works after passwords match when you press enter, you lose your button element. It is better to use a separate div or paragraph tag to display your message and keep your button as it is since it's part of the form.
Here is the change you can try
<span id="matchingPassword">
<button type="submit" value="submit">Sign Me Up!</button></span>
<p id="message"></p>
</fieldset>
var passConfirm = function() {
if (document.getElementById("Password").value == document.getElementById("ConfirmPassword").value) {
document.getElementById("message").style.color = "green";
document.getElementById("message").style.fontWeight = "Heavy";
document.getElementById("message").innerHTML = "Passwords match!"
} else {
document.getElementById("message").style.color = "red";
document.getElementById("message").style.fontWeight = "Heavy";
document.getElementById("message").innerHTML = "Passwords match!"
}
}
I'm creating a registration page and am currently attempting to store the inputs of the form into an array. I'm using
var form_inputs = document.getElementsByClassName("form_input");
to store the inputs in the same place, however if I try to alert form_inputs to test if anything is actually being stored, it just alerts "Undefined".
function validate_form(event) {
var forename = document.getElementById("forename");
var surname = document.getElementById("surname");
var username = document.getElementById("username");
var password = document.getElementById("password");
var re_password = document.getElementById("re_password");
var email = document.getElementById("email");
var errors = 0
var special_chars = "<>#!#$%^&*()_+[]{}?:;|'\"\\,./~`-=";
var form_inputs = document.getElementsByClassName("form_input");
if (forename.value == "") {
//document.getElementById("forename").style.background = "red";
forename_confirmation.style.visibility = 'visible';
var errors = errors + 1
} else
for (var i = 0; i < forename.value.length; i++) {
if (special_chars.indexOf(forename.value.charAt(i)) != -1) {
forename_chars.style.visibility = 'visible'
}
}
if (surname.value == "") {
//document.getElementById("surname").style.background = "red";
surname_confirmation.style.visibility = 'visible';
var errors = errors + 1
} else
for (var i = 0; i < surname.value.length; i++) {
if (special_chars.indexOf(surname.value.charAt(i)) != -1) {
surname_chars.style.visibility = 'visible'
}
}
if (username.value == "") {
//document.getElementById("username").style.background = "red";
username_confirmation.style.visibility = 'visible';
var errors = errors + 1
} else
for (var i = 0; i < username.value.length; i++) {
if (special_chars.indexOf(username.value.charAt(i)) != -1) {
username_chars.style.visibility = 'visible'
}
}
if (password.value == "") {
//document.getElementById("password").style.background = "red";
pass_confirmation.style.visibility = 'visible';
var errors = errors + 1
}
if (password.value != re_password.value) {
//document.getElementById("re_password").style.background = "red";
repass_confirmation.style.visibility = 'visible';
var errors = errors + 1
}
if (email.value == "") {
//document.getElementById("email").style.background = "red";
var errors = errors + 1
}
if (errors != "0") {
alert("Whoops! Looks like you didn't enter your details properly");
console.log(form_inputs);
event.preventDefault(); // Prevent the form from submitting
}
if (!email.value.includes("#") || !email.value.includes(".")) {
//document.getElementById("email").style.background = "blue";
email_confirmation.style.visibility = 'visible';
return false;
}
return (true);
}
<!DOCTYPE html>
<html>
<head>
<title>Login form</title>
<link rel="stylesheet" type="text/css" href="Login Form CSS.css">
<script src="Registration function.js" defer></script>
<body>
<div class="loginbox">
<img src="Logo.jpg" class="avatar">
<h1> Create Account </h1>
<form name="login-form">
<div id="forename_confirmation"> Please fill in this box </div>
<div id="forename_chars"> Don't use special characters</div>
<p>Forename
<p>
<input class="form_input" type="text" name="forename" id="forename" placeholder="Enter Forename here">
<div id="surname_confirmation"> Please fill in this box </div>
<div id="surname_chars"> Don't use special characters</div>
<p>Surname
<p>
<input class="form_input" type="text" name="surname" id="surname" placeholder="Enter Surname here">
<div id="username_confirmation"> Please fill in this box </div>
<div id="username_chars"> Don't use special characters</div>
<p>Username
<p>
<input class="form_input" type="text" name="username" id="username" placeholder="Enter Username here">
<div id="pass_confirmation"> Please fill in this box </div>
<div id="pass_chars">Don't use special characters</div>
<p>Password
<p>
<input class="form_input" type="password" name="password" id="password" placeholder="Enter Password here">
<div id="repass_confirmation"> Passwords do not match </div>
<p>Re-enter Password
<p>
<input class="form_input" type="password" name="re_password" id="re_password" placeholder="Re-enter your password here">
<div id="email_confirmation"> Please enter a valid email </div>
<p>Email
<p>
<input class="form_input" type="email" name="email" id="email" placeholder="Enter Email here">
<!--
<p>Gender<p>
<input type="radio" id="Male" name="Gender" value="Male">Male</input>
<input type="radio" id="Female" name="Gender" value="Female">Female</input>
-->
<button onclick="validate_form(event)" type="Submit" value="True" name="button-submit"> Submit </button>
<br />
<br />
Forgot your password?
<br />
Already got an account?
<br /><br />
</form>
<!-- <button onclick="validate_form()" type="submit"> Validate </button> -->
</div>
</body>
</head>
<script>
forename_confirmation.style.visibility = 'hidden'
forename_chars.style.visibility = 'hidden'
surname_confirmation.style.visibility = 'hidden'
surname_chars.style.visibility = 'hidden'
username_confirmation.style.visibility = 'hidden'
username_chars.style.visibility = 'hidden'
pass_confirmation.style.visibility = 'hidden'
pass_chars.style.visibility = 'hidden'
repass_confirmation.style.visibility = 'hidden'
email_confirmation.style.visibility = 'hidden'
</script>
</body>
Array.from(document.getElementsByClassName("form_input")).forEach(
function(element, index, array) {
alert(element.innerHTML)
}
);
this will alert you of those elements
Can someone help me make this alert look much nicer? Like Maybe split up Each text box on its own line? I can not figure out how to make this look a lot cleaner and not just all piled on one line.
To see alert hit Lien radio button and then hit next without filling textboxes
http://jsfiddle.net/t4Lgm0n2/9/
function validateForm(){
var QnoText = ['lien']; // add IDs here for questions with optional text input
var ids = '';
flag = true;
for (i=0; i<QnoText.length; i++) {
CkStatus = document.getElementById(QnoText[i]).checked;
ids = QnoText[i]+'lname';
var eD = "";
if (CkStatus && document.getElementById(ids).value == '') {
eD = eD+' lienholder name';
document.getElementById(ids).focus();
flag = false;
}
ids2 = QnoText[i]+'laddress';
if (CkStatus && document.getElementById(ids2).value == '') {
eD=eD+' lienholder address';
document.getElementById(ids2).focus();
flag = false;
}
ids3 = 'datepicker2';
if (CkStatus && document.getElementById(ids3).value == '') {
eD=eD+' lien date';
document.getElementById(ids3).focus();
flag = false;
}
if(eD!="") alert("Please enter "+eD);
}
return flag;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<input type="radio" value="Yes" name="lien" id="lien" required="yes" onchange="showhideForm(this.value);"/><label for="lien">Lien</label>
<input type="radio" value="None" name="lien" id="nolien" onchange="showhideForm(this.value);"/><label for="nolien">No Lien</label>
<script type="text/javascript">
function showhideForm(lien) {
if (lien == "Yes") {
document.getElementById("div1").style.display = 'block';
document.getElementById("div2").style.display = 'none';
}
else if (lien == "None") {
document.getElementById("div2").style.display = 'block';
document.getElementById("div1").style.display = 'none';
$("#div1 > .clearfix input:text").val("");
}
}
</script>
<div id="div1" style="display:none">
<div class="clearfix">
<label for="lname">Lienholder Name:</label>
<input type="text" name="lienlname" validateat="onSubmit" validate="maxlength" id="lienlname" size="54" maxlength="120" message="Please enter lienholder name." value="">
</p>
<p>
<label for="laddress">Lienholder Address:</label>
<input type="text" name="lienladdress" validateat="onSubmit" validate="maxlength" id="lienladdress" size="54" maxlength="120" message="Please enter lienholder address." value="">
</p>
<p>
<label for="ldate">Date of Lien:</label>
<input type="text" name="lienldate" id="datepicker2" mask="99/99/9999" value="">
</div>
</div>
<div id="div2" style="display:none">
<!---You are not qualified to see this form.--->
</div>
<input type="submit" name="submit" value="Next" onclick="validateForm()">
You can use new line characters \n to make text more readable:
var eD = [];
if (CkStatus && document.getElementById(ids).value == '') {
eD.push('Please enter lienholder name');
document.getElementById(ids).focus();
flag = false;
}
// ...
if (eD.length) alert(eD.join('\n'));
As you can see I'm also pushing error messages into ed array, which makes it more convenient to concatenate resulting message using .join() method.
Demo: http://jsfiddle.net/t4Lgm0n2/11/
I'm new to the web programming can you please tell me what's wrong with following code?
<!doctype html>
<html>
<head>
<title>Form Validation</title>
<script type="text/javascript">
function validate (form) {
// valriable declaration
var returnValue = true;
var username = form.txtUserName.value;
var password1 = form.txtPassword.value;
var password2 = form.txtPassword2.value;
// check for UserName length
if (username.length < 6) {
returnValue = false;
alert("Your username must be at least\n6 characters long.\nPlease try again.");
frmRegister.txtUserName.focus();
};
// check for password length
if (password1.length < 6) {
returnValue = false;
alert("Your password must be at least\n6 characters long.\nPlease try again.");
frmRegister.txtPassword.value = "";
frmRegister.txtPassword2.value = "";
frmRegister.txtPassword.focus();
};
// check for match of password field
if (password1.value != password2.value) {
returnValue = false;
alert("Your password entries did not match.\nPlease try again.");
frmRegister.txtPassword.value = "";
frmRegister.txtPassword2.value = "";
frmRegister.txtPassword.focus();
};
return returnValue;
}
</script>
</head>
<body>
<form method="post" name="frmRegister" action="register.html" onsubmit="return validate(this);">
<div><label for="txtUsername">UserName : </label>
<input type="text" name="txtUserName" id="txtUserName" size="12" />
</div>
<div><label for="txtPassword">Password : </label>
<input type="text" name="txtPassword" id="txtPassword" size="12" />
</div>
<div>
<label for="txtPassword2">Confirm your password : </label>
<input type="text" name="txtPassword2" id="txtPassword2" size="12" />
</div>
<div>
<input type="submit" value="Log in" />
</div>
</form>
</body>
</html>
first of all stop using return from event handler.
convert your code to
<form ... onsubmit="validate(event,this)">
change your function to validate(event,form);
wherever you feel form should not be submitted..
write :
event.preventDefault()
instead of return false
Demonstration :
http://codepen.io/anon/pen/kGmeL
I want to make a loginform using pure javascript (no libraries) and I have 2 problems!
SOLVED! by Grainier Perera
When username.value.length hits 4 characters usernameInfo.innerHTML changes back to "Please type ypur username" ! The problem is passwordInfo.innerHTML changes to "At least 6 characters" as soon as username.value.length hits 4 characters. So here is my first problem. I want passwordInfo.innerHTML to change only when I start typing in password field (onkeyup).
My second problem. When I submit the form with empty fields I want both usernameInfo.innerHTML and passwordInfo.innerHTML to change, not only usernameInfo.innerHTML.
To make it easier for u to understand the code I'll paste it all here so you can just copy it and try it yourself. Thank you!
<!DOCTYPE html>
<html>
<head>
<style>
form label {display:block; margin-top:5px;margin-left:3px;font:12px Arial;color:gray;}
form input {width:200px;padding:5px;display:inline-block; margin-top:5px;}
#submit {padding:7px;background-color:#f7af38; border:#f7af38;width:215px;display:inline-block;margin-top:15px;font:11px Tahoma;color:black;}
#usernameInfo {display:inline-block; font:italic 12px Arial; color:gray;}
#passwordInfo {display:inline-block; font:italic 12px Arial; color:gray;}
#finalInfo {font:italic 12px Arial; margin-left:5px;}
</style>
</head>
<body>
<form method="post" action="login.php" onsubmit="return validate();">
<label>Username</label>
<input id="username" name="username" type="text" onkeyup="return validate();" />
<span id="usernameInfo"></span>
<label>Password</label>
<input id="password" name="password" type="password" onkeyup="return validate();" />
<span id="passwordInfo"></span>
<br />
<input type="submit" id="submit" name="submit" />
<span id="finalInfo"></span>
</form>
<script type="text/javascript">
document.getElementById('usernameInfo').innerHTML = "Please type your username!";
document.getElementById('passwordInfo').innerHTML = "Please type your password!";
function validate()
{
var username = document.getElementById('username');
var usernameInfo = document.getElementById('usernameInfo');
var password = document.getElementById('password');
var passwordInfo = document.getElementById('passwordInfo');
if(username.value.length < 4){
usernameInfo.style.color='red';
usernameInfo.innerHTML = "At least 4 characters!";
return false;
}
else{
usernameInfo.style.color='gray';
usernameInfo.innerHTML = "Please type your username!";
}
if(password.value.length < 6){
passwordInfo.style.color='red';
passwordInfo.innerHTML = "At least 6 characters!";
return false;
}
else{
passwordInfo.style.color='gray';
passwordInfo.innerHTML = "Please type your password!";
}
}
</script>
</div>
</body>
</html>
Try This
HTML
<form method="post" action="login.php" onsubmit="return validateForm();">
<label>Username</label>
<input id="username" name="username" type="text" onkeyup="return validateUserName();" />
<span id="usernameInfo"></span>
<label>Password</label>
<input id="password" name="password" type="password" onkeyup="return validatePassWord();" />
<span id="passwordInfo"></span>
<br />
<input type="submit" id="submit" name="submit" />
<span id="finalInfo"></span>
</form>
JavaScript
document.getElementById('usernameInfo').innerHTML = "Please type your username!";
document.getElementById('passwordInfo').innerHTML = "Please type your password!";
function validateUserName()
{
var username = document.getElementById('username');
var usernameInfo = document.getElementById('usernameInfo');
if(username.value.length < 4){
usernameInfo.style.color='red';
usernameInfo.innerHTML = "At least 4 characters!";
return false;
}
else{
usernameInfo.style.color='gray';
usernameInfo.innerHTML = "Please type your username!";
return true;
}
}
function validatePassWord()
{
var password = document.getElementById('password');
var passwordInfo = document.getElementById('passwordInfo');
if(password.value.length < 6){
passwordInfo.style.color='red';
passwordInfo.innerHTML = "At least 6 characters!";
return false;
}
else{
passwordInfo.style.color='gray';
passwordInfo.innerHTML = "Please type your password!";
return true;
}
}
function validateForm()
{
var userValid = validateUserName();
var passValid = validatePassWord();
return userValid && passValid;
}
Working Sample : link