Remove form error with correct input - javascript

I just made a registration form which will tell you in red(CSS) letters if something is wrong. However I want this text to go away as soon as the user writes it correctly. How do I do that?
<script>
function validateForm2() {
var usrnm2 = document.getElementById("usrnm2").value;
var passw2 = document.getElementById("passw2").value;
var cnfpassw2 = document.getElementById("cnfpassw2").value;
var age = document.getElementById("age").value;
if (usrnm2 == null || usrnm2 == "") {
document.getElementById("error1").innerHTML = "You must enter a username";
return false;
}
else if (passw2 == null || passw2 == "") {
document.getElementById("error2").innerHTML = "You must enter a password";
return false;
}
else if (cnfpassw2 !== passw2) {
document.getElementById("error3").innerHTML = "Password does not match";
return false;
}
else if (age < 18) {
document.getElementById("error4").innerHTML = "You are not old enough to enter this site"
return false;
}
else {
alert("Congratulations, you have registered successfully!")
}
}
</script>
<script>
function register2() {
validateForm2()
}
</script>
<form>
Username:
<input id="usrnm2" type="text" name="username"><p id="error1"></p>
Password
<input id="passw2" type="password" name="password"><p id="error2"></p>
Confirm Password
<input id="cnfpassw2" type="password" name="confirmpw2"><p id="error3"></p>
Age
<input id="age" type="number" name="age"><p id="error4"></p><br />
<input id="bttn2" type="button" value="Register!" onclick="register2()"><br />
</form>

Separate the validation conditions into single block if statements, and then include a handler for returning the fields to normal when they are entered correctly:
if (field is entered incorrectly) {
document.getElementById("error").innerHTML = "You must enter correctly";
return false;
}
else {
document.getElementById("error").innerHTML = "";
}
...
alert("Congratulations, you have registered successfully!");
You simply need to place the alert after all of the statements - it will execute as long as none of the conditions fail and thus return.

Related

I want to make a registration form but the script wont work the way i want

To validate the checkpoint the form will have to show an alert if
One of the inputs is empty
The password has less than 8 characters
Doesn't have a valid e-mail adress
The password must be a combination of charatacters , numbers and at least a capital letter
And finally the reset button will reset all the inputs to empty :
//Variable declaration
var username=document.forms["Registration"]["name"];
var e_mail=document.forms["Registration"]["email"];
var password=document.forms["Registration"]["psw1"];
var passwordcheck=document.forms["Registration"]["psw2"];
//add eventListener
username.addEventListener("blur", NameVerify, true);
e_mail.addEventListener("blur", EmailVerify, true);
password.addEventListener("blur", PasswordVerify, true);
passwordcheck.addEventListener("blur", PasswordVerify, true);
// validate the registration
function Validate(){
if (username.value=="")
{
alert("username is required");
username.focus()
return false;
}
if (e_mail.value=="")
{
alert("Email is required");
e_mail.focus()
return false;
}
if (password.value=="")
{
alert("Password is required");
password.focus()
return false;
}
if (passwordcheck.value=="")
{
alert("Re-enter your password");
passwordcheck.focus()
return false;
}
if(password.value != passwordcheck.value){
alert("Password do not match!!")
passwordcheck.focus()
return false;
}
}
//check the username value
function NameVerify(username){
if (username.value !=0) {
document.querySelector.backgroundColor = lightGrey;
return true;
}
}
//check the e_mail
function EmailVerify(e_mail){
if (/^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.`\w{2,3})+$/.test(Registration.email.value))`
{
return (true)
}
alert("You have entered an invalid email address!")
e_mail.focus()
return (false)
}
//check the password
function PasswordVerify(password){
var psw = /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[^a-zA-Z0-9])(?!.*\s).{8,20}$/;
if(password.value.match(psw))
{
alert('Correct, try another...')
return true;
}
else
{
alert('Wrong!!')
return false;
}
}
// clear all text inputs when the page is loaded
function clearInp() {
document.getElementsByTagName("input").value = "";
return true;
}
//reset all text fields
function Reset() {
document.querySelector("#Registration").reset();
return true;
}
None of this requires any JavaScript at all.
One of the inputs is empty
<input type="text" required />
The password has less than 8 characters
<input type="password" minlength="8" />
Doesn't have a valid e-mail adress
<input type="email" />
The password must be a combination of charatacters , numbers and at least a capital letter
<input type="password" pattern="(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9]).{8,}" />
And finally the reset button will reset all the inputs to empty
<input type="reset" value="Reset form" />
Once you've eliminated all JavaScript code from your form, you will find that your form no longer has any JavaScript errors ;)

This javascript form validation won't go through even when the fields have been filled in. Any advice?

<script type="text/javascript">
function checkforinput() {
if (document.getElementById('fname').value == "") {
document.getElementById('fname').style.borderColor = "red";
document.getElementById('errMsg').innerHTML = "*Please enter First and Last Name";
} else {
document.getElementById('fname').style.borderColor = "#c5c5c5";
document.getElementById('errMsg').innerHTML = "";
}
if (document.getElementById('lname').value == "") {
document.getElementById('lname').style.borderColor = "red";
document.getElementById('errMsg2').innerHTML = "*Please enter First and Last Name";
} else {
document.getElementById('lname').style.borderColor = "#c5c5c5";
document.getElementById('errMsg2').innerHTML = "";
}
if (document.getElementById('email').value == "") {
document.getElementById('email').style.borderColor = "red";
document.getElementById('errMsg3').innerHTML = "*Please enter a valid email";
} else {
document.getElementById('email').style.borderColor = "#c5c5c5";
document.getElementById('errMsg3').innerHTML = "";
}
return false;
}
</script>
Hey guys. So my question is regarding this chunk of Javascript code. So these inputs (fname, lname, and email) have a span right next to them with the id errMsg that will display whatever the value of .innerHTML is. The validation works. Except whenever I fill in all the fields completely, my submit button won't process the form action i have in place. Nothing happens. Any ideas as to why this is happening. I feel it has to do something with the ELSE in the conditional statement but i don't know what it is exactly. The reason I use ELSE here, is because it turns the field back to how it looked like before. But maybe its actually screwing me over here. I need help guys. Any advice is appreciated.
This is my HTML code:
<form name="postform" action="postingprocessed.php" method="post" onsubmit="return checkforinput()">
<div class="fullName">
<input id="fname" type="text" maxlength="100" placeholder="First Name" name="first_name" /><span id="errMsg"></span>
<input id="lname" type="text" maxlength="100" placeholder="Last Name" name="last_name" /><span id="errMsg2"></span>
</div>
<input id="email" class="text" type="email" maxlength="100" placeholder="Email" name="email" /><span id="errMsg3"></span>
<br>
<input id="submitBtn" class="submitBtn" type="submit" value="Post This!" name="SubmitBtn" />
</form>
my submit button won't process the form action i have in place. Nothing happens.
Because you always return false, which tells browser not to process form. Return false only if some field is invalid and true otherwise:
var valid = true;
if (document.getElementById('fname').value == "") {
document.getElementById('fname').style.borderColor = "red";
document.getElementById('errMsg').innerHTML = "*Please enter First and Last Name";
valid = false;
} else {
document.getElementById('fname').style.borderColor = "#c5c5c5";
document.getElementById('errMsg').innerHTML = "";
}
// ...
return valid;
Another recommendation. Don't use styles like your are now, this makes your code pretty obtrussive, verbose and hard to maintain (imagine, you want to change error border color - you need to change it on every field). Use CSS classes instead.
This will only submit the form if all the input is valid :) What we're doing is set flag=1 if any input is empty/invalid and in the end if flag is 1, form won't be submitted otherwise it will be submitted.
<script type="text/javascript">
function checkforinput() {
var flag=0;
if (document.getElementById('fname').value == ""){
document.getElementById('fname').style.borderColor = "red";
document.getElementById('errMsg').innerHTML = "*Please enter First and Last Name";
flag=1;
}
else {
document.getElementById('fname').style.borderColor = "#c5c5c5";
document.getElementById('errMsg').innerHTML = "";
}
if (document.getElementById('lname').value == ""){
document.getElementById('lname').style.borderColor = "red";
document.getElementById('errMsg2').innerHTML = "*Please enter First and Last Name";
flag=1;
}
else {
document.getElementById('lname').style.borderColor = "#c5c5c5";
document.getElementById('errMsg2').innerHTML = "";
}
if (document.getElementById('email').value == ""){
document.getElementById('email').style.borderColor = "red";
document.getElementById('errMsg3').innerHTML = "*Please enter a valid email";
flag=1;
}
else {
document.getElementById('email').style.borderColor = "#c5c5c5";
document.getElementById('errMsg3').innerHTML = "";
}
if(flag)
return false;
else
return true;
}
</script>

Javascript - Executing all the validation functions on form submit

I am currently working on an Email form and have little experience with javascript but am close to accomplishing what I need but struggling at one point, spent hours trying everything I can find searching and figured someone on here would probably have my answer instantly.
I currently have 3 functions checking a box is filled, email is correct format and passwords match.
If I set each function to run on its own upon clicking submit they work perfectly for their own intended purpose, however I am having trouble working out how to make it so that all 3 functions are run upon hitting submit. My final attempt which seems closest is adding the validateForm function at the bottom of my scripts to run all scripts but this did not seem to work. Hopefully something small I am overlooking, appreciate any help.
HTML:
<form name="registerkeys" form action="form.php" method="post" onsubmit="return validateForm();">
First Name: <input type="text" name="first_name"><br>
Last Name: <input type="text" name="last_name"><br>
Email: <input type="text" name="email"><br>
Phone Number: <input type="text" name="phonenumber"><br>
Information on Key: <input type="text" name="keyinfo"><br>
Password: <input type="password" name="password" id="password"></label><br>
Verify Password: <input type="password" name="passwordverify" id="passwordverify"><br>
Password Hint: <input type="text" name="passwordhint"><br>
<textarea rows="5" name="message" cols="30" placeholder="Comments:"></textarea><br>
<input type="submit" name="submit" value="Submit">
</form>
Javascript:
function validateFill(){
var x=document.forms["registerkeys"]["first_name"].value;
if (x==null || x=="") {
alert("First name must be filled out");
return false;
}
var x=document.forms["registerkeys"]["last_name"].value;
if (x==null || x=="") {
alert("Last name must be filled out");
return false;
}
var x=document.forms["registerkeys"]["phonenumber"].value;
if (x==null || x=="") {
alert("Phone number must be filled out");
return false;
}
var x=document.forms["registerkeys"]["keyinfo"].value;
if (x==null || x=="") {
alert("Key info must be filled out");
return false;
}
var x=document.forms["registerkeys"]["pass1"].value;
if (x==null || x=="") {
alert("Password must be filled out");
return false;
}
var x=document.forms["registerkeys"]["passwordhint"].value;
if (x==null || x=="") {
alert("Password hint must be filled out");
return false;
}
}
function validateEmail()
{
var x=document.forms["registerkeys"]["email"].value;
var atpos=x.indexOf("#");
var dotpos=x.lastIndexOf(".");
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length)
{
alert("Not a valid e-mail address");
return false;
}
}
function validatePassword(){
var password = document.getElementById("password").value;
var passwordverify = document.getElementById("passwordverify").value;
var ok = true;
if (password != passwordverify) {
alert("Passwords Do not match");
document.getElementById("password").style.borderColor = "#E34234";
document.getElementById("passwordverify").style.borderColor = "#E34234";
ok = false;
}
else {
alert("Passwords Match!!!");
}
return ok;
}
function validateForm(){
var a = validateFill();
var b = validateEmail();
var c = validatePassword();
return a && b && c;
}
Your validateFill() and validateEmail() function should return true at the end.
validateFill() only returns false if validation has not passed, but never true. You should add return true at the end of the function, outside of conditions.
validateEmail() returns false if email is invalid but you are missing the return true if email is valid.
Also, to prevent duplicate popups I suggest that you change your validateForm() to something like this:
function validateForm() {
var a = validateFill();
if (a) var b = validateEmail();
else var b = false;
if (a&&b) var c = validatePassword();
else var c = false;
return a && b && c;
}
So it only checks one function until it passes, and then checks the next.
validateFill() and validateEmail() should return true at the end (right now they return nothing if validation passed.
validatePassword() should return true instead of ok.

JavaScript double form validation

I am new to JavaScript and I have been doing a university assignment based around HTML and JavaScript. In this assignment I was asked to create a number of forms to allows a person to register for some form of educational classes. I was asked to create the form using HTML and to validate the entries using only JavaScript.
What I have been struggling to figure out is how to validate more than one form input using one block of validation (if that is possible), I want to validate both the firstname and familyname inputs using only validateForm.
Here is a segment I have been testing out:
<head>
<script>
function validateForm() {
var x = document.forms["nameform"]["firstname"].value;
if (x == null || x == "") {
alert("first name must be filled out");
return false;
}
}
</script>
</head>
<body>
<form name="nameform" , action="demo_form.asp" , onsubmit="return validateForm()" , method="post">
<b>First name:</b>
<input type="text" name="firstname">
<br>
<b>Family name:</b>
<input type="text" name="familyname">
<br>
<input type="submit" value="Submit">
</form>
</body>
Any help would be greatly appreciated!
<head>
<script>
function validateForm()
{
var firstname=document.getElementById('txtfirstname');
var familyname=document.getElementById('txtfamilyname');
if (firstname.value=="")
{
alert("first name must be filled out");
return false;
}
if (familyname.value=="")
{
alert("familyname must be filled out");
return false;
}
}
</script>
</head>
<body>
<form name="nameform", action="demo_form.asp", onsubmit="return validateForm()", method="post">
<b>First name:</b> <input type="text" id="txtfirstname" name="firstname">
<br>
<b>Family name:</b> <input type="text" id="txtfamilyname" name="familyname">
<br>
<input type="submit" value="Submit">
</form>
</body>
You can check all inputs, store error messages (if any) and return false at the end if there is even one failure.
i.e.
function validateForm() {
var x = document.forms["nameform"]["firstname"].value, errors = [];
if (x == null || x == "") {
errors.push("first name must be filled out");
}
x = document.forms["nameform"]["familyname"].value;
if (x == null || x == "") {
errors.push("family name must be filled out");
}
if(errors.length > 0) { // check if there were any errors
alert(errors.join("\n")); // alert all messages together
return false;
}
}
Couple of possibilities...
<script>
function validateForm()
{
var x=document.forms["nameform"]["firstname"].value;
if (x==null || x=="")
{
alert("first name must be filled out");
return false;
}
x=document.forms["nameform"]["lasttname"].value;
if (x==null || x=="")
{
alert("last name must be filled out");
return false;
}
return true;
}
</script>
will present an alert for each field as it fails validation and return true if all fields are OK.
<script>
function validateForm()
{
var errorString="";
var x=document.forms["nameform"]["firstname"].value;
if (x==null || x=="")
{
errorString+="first name must be filled out\n";
}
x=document.forms["nameform"]["lasttname"].value;
if (x==null || x=="")
{
errorString+="last name must be filled out\n";
}
if(errorString=="")
{
return true;
}
else
{
alert(errorString);
return false;
}
}
</script>
will return a single alert listing all of the fields that have failed validation.
In addition, I always like to use the focus() method on the first field that failed validation to put the cursor in the field that needs correcting.
Try this..
function validateForm()
{
var msg='';
var flag=false;
var x = document.forms["nameform"]["firstname"].value;
if (x == null || x == "")
{
flag = true;
msg = ' First Name '
}
x = document.forms["nameform"]["familyname"].value;
if (x == null || x == "")
{
if(flag==true)
msg = msg + 'And Family Name '
else
msg = msg + ' Family Name ';
flag = true;
}
if (flag==true) {
msg = msg + " must be filled out";
alert(msg);
}
return false;
}
simply store it in multiple variables and have multiple if statements:
<script>
function validateForm() {
// name the variables appropriately
var firstname = document.forms["nameform"]["firstname"].value;
var familyname = document.forms["nameform"]["familyname"].value;
// check if either of them are correct, if not alert and return false.
if (firstname == null || firstname == "") {
alert("first name must be filled out");
return false;
} else if (familyname == null || familyname == ""){
alert("family name must be filled out");
return false;
}
return true;
}
</script>

JavaScript form validation on server/local

I'm using JavaScript form validation for the entry form for a contest I'm running. It's inline CSS so that if certain conditions aren't met, it displays, in red, messages that say "please enter your email address" or "that doesn't look like a valid email address" etc.
The script, which sits at the top of the file, looks like this:
<script>
function checkForm() {
name = document.getElementById("name").value;
email = document.getElementById("email").value;
terms = document.getElementById("terms").value;
if (name == "") {
hideAllErrors();
document.getElementById("nameError").style.display = "inline";
document.getElementById("name").select();
document.getElementById("name").focus();
return false;
} else if (email == "") {
hideAllErrors();
document.getElementById("emailError").style.display = "inline";
document.getElementById("email").select();
document.getElementById("email").focus();
return false;
}
else if (!check_email(document.getElementById("email").value)) {
hideAllErrors();
document.getElementById("emailError2").style.display = "inline";
document.getElementById("email").select();
document.getElementById("email").focus();
return false;
}
else if (!document.form1.terms.checked){
hideAllErrors();
document.getElementById("termsError").style.display = "inline";
document.getElementById("terms").select();
document.getElementById("terms").focus();
return false;
}
return true;
}
function check_email(e) {
ok = "1234567890qwertyuiop[]asdfghjklzxcvbnm.#-_QWERTYUIOPASDFGHJKLZXCVBNM";
for(i=0; i < e.length ;i++){
if(ok.indexOf(e.charAt(i))<0){
return (false);
}
}
if (document.images) {
re = /(#.*#)|(\.\.)|(^\.)|(^#)|(#$)|(\.$)|(#\.)/;
re_two = /^.+\#(\[?)[a-zA-Z0-9\-\.]+\.([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
if (!e.match(re) && e.match(re_two)) {
return (-1);
}
}
}
function hideAllErrors() {
document.getElementById("nameError").style.display = "none"
document.getElementById("emailError").style.display = "none"
document.getElementById("commentError").style.display = "none"
document.getElementById("termsError").style.display = "none"
}
The email and name validation work just fine, the part of the form that won't work looks like this:
<form onSubmit="return checkForm();" method="get" action="sweepstakes-results.php"
<input type=checkbox name=terms id=terms ><br></p>
<div class=error id=termsError>Required: Please check the checkbox<br></div>
<p><input type=submit value=Send style="margin-left: 50px"> </p>
</form>
The "terms and conditions" checkbox only works if the file is on my local machine, when I upload it, it just lets me submit the form even if it's not checked. Isn't JavaScript run on the browser? How could the location of the file make a difference?
Your form doesn't have a name, so the following code won't work:
else if (!document.form1.terms.checked){
Since you're already retrieving the DOM object of the checkout, do the following. Change the line:
terms = document.getElementById("terms").value;
to:
terms = document.getElementById("terms");
And the replace that else if code with:
else if (!terms.checked){

Categories