Validating form after error has been shown - javascript

I have a form where username and password are entered. If they are left blank an error is shown, however when one of the input box is filled in and the submit button is clicked the error that's there doesn't go away.
<script type="text/javascript">
function chck() {
var valid = true;
var pass = document.getElementById('password_box').value;
var user = document.getElementById('username_box').value;
if (user == '') {
document.getElementById('password-error').innerHTML = "* Please enter username to proceed...";
document.getElementById('username_box').style.borderColor = "#DC3D24";
document.getElementById('username_box').style.backgroundColor = "maroon";
valid = false;
}
if (pass == '') {
document.getElementById('user-error').innerHTML = "* Please enter password to proceed...";
document.getElementById('password_box').style.borderColor = "#DC3D24";
document.getElementById('password_box').style.backgroundColor = "maroon";
valid = false;
}else{
valid = true;
}
return valid;
}
</script>
</head>
<body>
<form action="checkup.php" method="post" name="checkup">
<div class="login-box">
<input type="text" placeholder="Username goes here.." id="username_box" class="box" name="username">
<input type="password" placeholder="Password goes here.." id="password_box" class="box" name="password"> <BR>
<input type="submit" class="button" id="submit_button" value="LogMeIn" onClick="return chck()">
<input type="button" class="button" id="clear_button" value="Clear">
</div>
</form> <BR>
<center>
<div class="error-area" id="message">
<p id="password-error">
</p>
<p id="user-error">
</p>
</div>
</center>
Only if I fill in both boxes, then the error goes away. I want to hide the error as soon as one of the boxes is filled in with text. Thanks for any help you can give me.

Try using HTML5......just add required attribute and to clear values use reset input
<form action="checkup.php" method="post" name="checkup">
<div class="login-box">
<input type="text" placeholder="Username goes here.." id="username_box" class="box" name="username" required title="* Please enter username to proceed...">
<input type="password" placeholder="Password goes here.." id="password_box" class="box" name="password" required title="* Please enter password to proceed..."> <BR>
<input type="submit" class="button" id="submit_button" value="LogMeIn" onClick="return chck()">
<input type="reset" value="Clear">
</div>
</form>
or if you want to achieve this with the existing code try using onfocus event to clear the error message. Hope this hepls

You could run chck() on the "keypress" event for your "username_box" and "password_box" elements.
Like so:
document. getElementById("username_box").addEventListener("keypress", function () {
chck();
}, true);
but update chck slightly to be:
function chck() {
var valid = true;
var pass = document.getElementById('password_box').value;
document.getElementById('password-error').innerHTML = "";
var user = document.getElementById('username_box').value;
document.getElementById('user-error').innerHTML = "";
document.getElementById('password_box').setAttribute("style", "");
document.getElementById('username_box').setAttribute("style", "");
if (user == '') {
document.getElementById('password-error').innerHTML = "* Please enter username to proceed...";
document.getElementById('username_box').style.borderColor = "#DC3D24";
document.getElementById('username_box').style.backgroundColor = "maroon";
valid = false;
}
if (pass == '') {
document.getElementById('user-error').innerHTML = "* Please enter password to proceed...";
document.getElementById('password_box').style.borderColor = "#DC3D24";
document.getElementById('password_box').style.backgroundColor = "maroon";
valid = false;
}
else{
valid = true;
}
return valid;
}

Related

Checking if the input fields are filled in properly (pure javascript)

I almost complete the form validation, but the only pain in the ass for me is:
1) Input fields should be checked themselves when some have filled in the input field and click outside the input box.
2) when someone leaves all the input fields empty and clicked on the send button.
Anyone an idea how I can fixed that?
function validateForm() {
var name = document.getElementById("name");
var email = document.getElementById("email");
var nameValidation = document.getElementById("nameValidation");
var emailValidation = document.getElementById("emailValidation");
var filter = /^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
if (name.value.length == "") {
nameValidation.innerHTML = " Please fill in your name";
name.focus();
} else {
nameValidation.innerHTML = " Right";
}
if(!filter.test(email.value) || (email.value.length == "")) {
emailValidation.innerHTML = " Please enter a valid email address";
email.focus();
}
else {
emailValidation.innerHTML = " Right!";
}
}
<form action="#" id="form" method="post" name="form">
<img id="close" src=IMAGE/close.png alt="close-button" onclick="div_hide()"/>
<h3><b>Application form</b></h3>
<input id="name" class="application" name="name" placeholder="Name" type="text" maxlength="30" /><span id="nameValidation"></span><br/>
><input id="email" class="application" placeholder="Email" type="text" maxlength="254" /><span id="emailValidation"></span>
<div id="upload-box">
<input id="upload" class="application upload" type="file"/>
<input id="submit" class="application apply-button" type="button" onclick="validateForm()" value="Send"/>
</div>
</form
<input type="email" required />
Job done.

Form validation: remove error after onkeydown in input

I am working on my first for validation, really basic.
If you leave the 'username' input blank it will turn the username input border red and also place an alert icon in the input.
I am trying to 'remove' what was added when the validation failed as soon as the user starts typing in the input that caused the error.
So the scenario is: The user leaves Username blank, clicks Submit and then the border of the Username input goes red and an error icon appears. They then go back and they add their username into the Username input after the first character they type into the Username box I want the red border and error icon to disappear.
However my attempts have failed
My Fiddle
JS
function contactForm() {
var theForm = document.forms.contact;
var errorUsername = document.getElementById('username-error');
var usernameInput = document.getElementById('username');
theForm.onsubmit = function() {
if (theForm.username.value === '') {
errorUsername.style.display = 'block';
usernameInput.className = 'form__input form__input--red rounded-4';
return false;
} else {
theForm.username.onkeydown = function() {
errorUsername.style.display = 'none';
usernameInput.className = 'form__input rounded-4';
};
return true;
};
};
};
contactForm();
HTML
<form name="contact" action="#" novalidate>
<div class="input__holder">
<input id="username" name="username" type="text" class="form__input rounded-4" placeholder="Username">
<div id="username-error" class="input__error">!</div>
</div>
<div class="input__holder">
<input name="password" type="password" class="form__input rounded-4" placeholder="Password">
</div>
<div class="input__holder">
<input name="email" type="text" class="form__input rounded-4" placeholder="E-mail">
</div>
<button type="submit" id="" class="submit-button rounded-4">Submit</button>
</form>
CSS
Too long, in Fiddle :)
You can add something like this on javascript
document.onkeyup = function() {
var errorUsername = document.getElementById('username-error');
var usernameInput = document.getElementById('username');
if (usernameInput.value.length === 0) return;
errorUsername.style.display = 'none';
usernameInput.className = 'form__input rounded-4';
}
Here the fiddle:
https://jsfiddle.net/12apmo5j/12/
I think this solves your problem :)

Using JavaScript to validate form both onblur and when pressing submit

I'm trying to validate fields in a form using JavaScript. The fields should be validated either when the user leaves a field (onblur) and when the user presses submit. The form should not be sent if the validation fails in any way on a required field.
The thing is I also have a JS function that if validation succeeds, should rewrite one of the fields that is validated, and send the form.
This is my HTML:
<head>
<meta charset='UTF-8'>
<script type="text/javascript" src="./library/checkcreateuser.js"></script>
<script type="text/javascript" src="./library/hashcreateuser.js"></script>
</head>
<body>
<div class="maindiv">
<form name="createform" id="createform" onsubmit="return formhash();" action="#" method="post">
<input type="text" name="email" id="email" onblur="checkEmail()" placeholder="E-postadress" maxlength="50" />
<label for="email" id="labemail"></label><br />
<input type="text" name="testemail" id="testemail" onblur="checkEmailConfirm()" placeholder="Bekräfta e-postadress" maxlength="50" /><br />
<label for="testemail" id="labtestemail"></label><br />
<br />
... other input fields that should be validated, not yet written ...
<br />
<input type="password" name="password" id="password" placeholder="Lösenord" maxlength="50" /><br />
<label for="password" id="labpassword"></label><br />
<input type="password" name="testpassword" id="testpassword" placeholder="Bekräfta lösenord" maxlength="50" /><br />
<label for="testpassword" id="labtestpassword"></label><br />
<br />
<input type="submit" placeholder="Registrera" onclick="validateForm()"><br />
</form>
</div>
</body>
And this is my javascript for validation:
function checkEmail() {
var validemail = true;
var email = document.getElementById("email");
var divided = email.split("#");
var divlen = divided.length;
if (divlen != 2) {
validemail = false;
document.getElementById("labemail").innerHTML = "Felaktig e-postadress";
} else {
document.getElementById("labemail").innerHTML = "<font color='#00cc00'>Korrekt epostadress</font>";
}
// More code to validate Email to come
return validemail;
}
function checkEmailConfirm() {
var validtestemail = true;
var email = document.getElementById("email");
var testemail = document.getElementById("email");
if (testemail != email) validtestemail = false;
return validtestemail;
}
function validateForm() {
var validform = true;
var returnval = true;
validform = checkEmail();
if (validform == false) returnval = false;
validform = checkEmailConfirm();
if (validform == false) returnval = false;
return returnval;
}
My problem is that nothing happens when i leave the email- or testemail-fields.
My second question is, if I want the form not submitted if any of the validations fails, but submitted and also hashed using the function called formhash() if the validations succeeds, is this the correct way?
EDIT: Using the Chrome debugger, i have the following errors:
Uncaught TypeError: undefined is not a function: checkcreateuser.js:9
checkEmail: checkcreateuser.js:9
onblur: newuser.php:16
to check for the value entered in email and testemail you should use:
var email = document.getElementById("email").value;
var testemail = document.getElementById("testemail").value;// then use split on these values.
if you will use
var email = document.getElementById("email");//you will get error may be like split is not a function or something similar.

Function never triggered by getElementById().addEventListener()

I'm attempting to move JavaScript event triggers on the two password fields (to alert the user if they're not equal) from within the form elements to
document.getElementById('id_password1').addEventListener('keyUp', checkPass);
document.getElementById('id_password2').addEventListener('keyUp', checkPass);
But the function is never triggered (if I change checkPass to checkPass() the function is called on page-load only, but I don't think this means it's being triggered by the listener). There are no errors in the JavaScript console. If I change the ids to something bogus, it gives this error:
Uncaught TypeError: Cannot read property 'addEventListener' of null
(I'm not familiar enough with the Chrome JavaScript inspector, to know if it can help me further.)
It all works properly if the event triggers are directly in the form elements.
Here are the form elements:
<p>Password: <input id="id_password1" name="password1" type="password" /></p>
<p>Password confirm: <input id="id_password2" name="password2" type="password" /></p>
What am I missing?
<HTML><HEAD>
<TITLE>Create account</TITLE>
</HEAD>
<BODY>
<h1>Create account</h1>
<form id="user_form" method="post" action="/accounts/register/">
<p>Username: <input id="id_username" maxlength="30" name="username" type="text" /> <span class="helptext">Required. 30 characters or fewer. Letters, digits and #/./+/-/_ only.</span></p>
<p>Password: <input id="id_password1" name="password1" type="password" /></p>
<p>Password confirm: <input id="id_password2" name="password2" type="password" /></p>
<span id="confirmMessage" class="confirmMessage"></span>
<input type="submit" name="submit" value="Register" />
</form>
<script language="JavaScript">
function checkPass() {
var pass1 = document.getElementById('id_password1');
var pass2 = document.getElementById('id_password2');
alert("pass1=" + pass1.value + ", pass2=" + pass2.value);
//Check passwords here. Set confirmMessage if bad.
}
document.getElementById('id_password1').addEventListener('keyUp', checkPass);
document.getElementById('id_password2').addEventListener('keyUp', checkPass);
</script>
</BODY></HTML>
The event is case sensitive. Try "keyup" (all lowercase) instead. See this fiddle:
http://jsfiddle.net/LfamexLw/
function checkPass(){
alert("keyup");
}
function checkPass2(){
alert("keyUp");
}
document.getElementById('id_password1').addEventListener('keyup', checkPass);
document.getElementById('id_password1').addEventListener('keyUp', checkPass2);
You'll notice checkPass2 never fires.
Here's the working code, based on #aquinas' answer, including the full check-the-password function:
<HTML><HEAD>
<TITLE>Create account</TITLE>
</HEAD>
<BODY>
<h1>Create account</h1>
<form id="user_form" method="post" action="/accounts/register/"
enctype="multipart/form-data">
<p><label for="id_username">Username:</label> <input id="id_username" maxlength="30" name="username" type="text" /> <span class="helptext">Required. 30 characters or fewer. Letters, digits and #/./+/-/_ only.</span></p>
<p><label for="id_password1">Password:</label> <input id="id_password1" name="password1" type="password" /></p>
<p><label for="id_password2">Password confirmation:</label> <input id="id_password2" name="password2" type="password" /></p>
<!-- Where checkPass() writes its message -->
<span id="confirmMessage" class="confirmMessage"></span>
<P><input type="submit" name="submit" value="Register" /></P>
</form>
<script language="JavaScript">
/*
From (8/27/2014)
http://keithscode.com/tutorials/javascript/3-a-simple-javascript-password-validator.html
Added the "don't print anything if one or both fields are empty" block
*/
function checkPass() {
//Store the password field objects into variables ...
var pass1 = document.getElementById('id_password1');
var pass2 = document.getElementById('id_password2');
//Store the Confimation Message Object ...
var message = document.getElementById('confirmMessage');
//Set the colors we will be using ...
var goodColor = "#66cc66";
var badColor = "#ff6666";
//Compare the values in the password field
//and the confirmation field
if(pass1.value.length === 0 || pass2.value.length === 0) {
pass2.style.backgroundColor = null;
message.style.color = null;
message.innerHTML = "";
return;
}
if(pass1.value === pass2.value){
//The passwords match.
//Set the color to the good color and inform
//the user that they have entered the correct password
pass2.style.backgroundColor = goodColor;
message.style.color = goodColor;
message.innerHTML = "Passwords Match!"
}else{
//The passwords do not match.
//Set the color to the bad color and
//notify the user.
pass2.style.backgroundColor = badColor;
message.style.color = badColor;
message.innerHTML = "Passwords Do Not Match!"
}
}
document.getElementById('id_password1').addEventListener('keyup', checkPass);
document.getElementById('id_password2').addEventListener('keyup', checkPass);
document.getElementById("id_username").focus();
</script>
</BODY></HTML>

Why isn't my instantaneous validation displaying anything?

I have a form that has a number of fields on it. When the user inputs anything, the field should automatically begin sending feedback as to whether or not the input is valid. The javascript code listed is suppose to handle the instantaneous feedback but it gives no reply whatsoever. It is also suppose to stop the form from being submitted if any of the user's input does not match the regular expressions. The regular expressions don't work either but they were working perfectly fine before I used the innerHTML. I would go back to using alerts if using innerHTML wasn't mandatory.
function insert() {
var valid = true;
document.getElementById("MessNM").innerHTML = "";
if (!document.getElementById("name").value.match(/^^[A-Z]{1}[a-z]{3,7}$/)) {
document.getElementById("MessNM").innerHTML = " Please input a proper name.";
valid = false;
}
document.getElementById("MessPS").innerHTML = "";
if (!document.getElementById("password").value.match(/^[a-zA-Z0-9]{4,8}$/)) {
document.getElementById("MessPS").innerHTML = " Please input a proper password with numbers and letters.";
valid = false;
}
document.getElementById("MessPSC").innerHTML = "";
if (document.getElementById("passwordcheck").value != document.getElementById("password").value) {
document.getElementById("MessPSC").innerHTML = " Password does not match.";
valid = false;
}
document.getElementById("MessAD").innerHTML = "";
if (!document.getElementById("address").value.match(/^[a-zA-Z0-9\s,'-]{5,40}$/)) {
document.getElementById("MessAD").innerHTML = " Address is not valid";
valid = false;
}
document.getElementById("MessZC").innerHTML = "";
if (!document.getElementById("zipcode").value.match(/^[0-9]{5}$/)) {
document.getElementById("MessZC").innerHTML = " Please input a proper Zipcode.";
valid = false;
}
if (!document.getElementById("zipcode").value.match(/^[0-9]{5}(-[0-9]{4})?$/)) {
document.getElementById("MessZC").innerHTML = " Please input a proper Zipcode.";
valid = false;
} else {
return valid;
}
}
function test() {
var result = true;
if (!insert()) {
result = false;
}
return result;
}
This is the html form that the javascript function is referencing.
<form name="Insert" id="I2" action="order.php" method="post" style="display: none;" onsubmit="return test()">
<p align="left">
<div id="texter">
<input type=text id="name" required="required" onkeyup="insert()" name="name" autocomplete="off" autofocus>Name <span id="MessNM"></span>
<br>
<input type=email id="email" required="required" onkeyup="insert()" name="email">Email Address <span id="MessEM"></span>
<br>
<input type=password id="password" required="required" onkeyup="insert()" name="password">Password <span id="MessPS"></span>
<br>
<input type=password id="passwordcheck" required="required" onkeyup="insert()" name="passwordcheck">Confirm Password <span id="MessPSC"></span>
<br>
<input type=text id="address" required="required" onkeyup="insert()" name="address">Address <span id="MessAD"></span>
<br>
<input type=text id="zipcode" required="required" onkeyup="insert()" name="zipcode">Zipcode <span id="MessZC"></span>
<br>
</div>
<input type="submit" value="submit" onclick="test()">
<input type="reset" value="Clear All">
<br>
<br>
</form>
There are several issues I see.
You have style="display: none;" on the form which makes the whole form invisible.
Your validation function returns false on the first failed validation which means you're only going to show an error message for the first invalid field, e.g. if e-mail address and zip code are invalid you'll only get a message for e-mail address.
The regular expression for the address validation is broken.
When the password confirmation error is fixed the error message doesn't clear.
By the fact that you say it was working when you used alerts, I'm guessing the main issue you're talking about is caused by the fact that each field validation returns false. You probably just had alerts before and returned a boolean at the end of the function. Here's a solution that addresses that issue and the others I mentioned above.
<form name="Insert" id="I2" action="order.php" method="post" onsubmit="return test()">
<p align="left">
<div id="texter">
<input type=text id="name" required="required" onkeyup="insert()" name="name" autocomplete="off"/>Name <span id="MessNM"></span>
<br>
<input type="email" id="email" required="required" onkeyup="insert()" name="email">Email Address <span id="MessEM"></span>
<br>
<input type="password" id="password" required="required" onkeyup="insert()" name="password">Password <span id="MessPS"></span>
<br>
<input type="password" id="passwordcheck" required="required" onkeyup="insert()" name="passwordcheck">Confirm Password <span id="MessPSC"></span>
<br>
<input type="text" id="address" required="required" onkeyup="insert()" name="address">Address <span id="MessAD"></span>
<br>
<input type="text" id="zipcode" required="required" onkeyup="insert()" name="zipcode">Zipcode <span id="MessZC"></span>
<br>
</div>
<input type="submit" value="submit" onclick="test()">
<input type="reset" value="Clear All">
<br>
<br>
</form>
function insert() {
var valid = true;
document.getElementById("MessNM").innerHTML = "";
if (!document.getElementById("name").value.match(/^^[A-Z]{1}[a-z]{3,7}$/)) {
document.getElementById("MessNM").innerHTML = " Please input a proper name.";
valid = false;
}
document.getElementById("MessPS").innerHTML = "";
if (!document.getElementById("password").value.match(/^[a-zA-Z0-9]{4,8}$/)) {
document.getElementById("MessPS").innerHTML = " Please input a proper password with numbers and letters.";
valid = false;
}
document.getElementById("MessPSC").innerHTML = "";
if (document.getElementById("passwordcheck").value != document.getElementById("password").value) {
document.getElementById("MessPSC").innerHTML = " Password does not match.";
valid = false;
}
document.getElementById("MessAD").innerHTML = "";
if (!document.getElementById("address").value.match(/^[a-zA-Z0-9\s,'-]*$/)) {
document.getElementById("MessAD").innerHTML = " Address is not valid";
valid = false;
}
document.getElementById("MessZC").innerHTML = "";
if (!document.getElementById("zipcode").value.match(/^[0-9]{5}$/)) {
document.getElementById("MessZC").innerHTML = " Please input a proper Zipcode.";
valid = false;
}
if (!document.getElementById("zipcode").value.match(/^[0-9]{5}(-[0-9]{4})?$/)) {
document.getElementById("MessZC").innerHTML = " Please input a proper Zipcode.";
valid = false;
}
return valid;
}

Categories

Resources