Add and Remove attribute in javascript - javascript

My problem is when I click submit, it should add the box class only for empty fields. But my code adds the box class for both filled and unfilled fields.
function validate() {
var a = document.forms["Form"]["uname"].value;
var b = document.forms["Form"]["number"].value;
var c = document.forms["Form"]["mail"].value;
if (a == null || a == "", b == null || b == "", c == null || c == "") {
['uname', 'mobNo', 'mail'].forEach(function(ids) {
document.getElementById(ids).style.border = "1px solid red";
});
return false;
} else if (!a.match(/^([a-zA-Z]{2,30})$/)) {
document.getElementById('uname').className = 'box';
return false;
} else if (!b.match(/^\d*[0-9](|.\d*[0-9]|,\d*[0-9])?$/)) {
document.getElementById('mobNo').className = 'box';
return false;
} else if (!c.match(/^([\w-\.]+#([\w-]+)+(\.[\w-]{2,4})?)$/)) {
document.getElementById('mail').className = 'box';
return false;
}
}
.box {
border: 2px solid red;
}
<html>
<head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<form method="post" name="Form" onsubmit="return validate()" action="" id="form_id">
<fieldset>
<label>NAME:</label>
<input type="text" name="uname" id="uname" class="fields">
<label>MOBILE NUMBER:</label>
<input type="text" name="number" id="mobNo" class="fields" minlength="10" maxlength="10">
<label>EMAIL:</label>
<input type="email" name="mail" id="mail" class="fields">
<button type="submit" name="submit">SUBMIT</button>
</fieldset>
</form>
</body>
</html>

There is bug in your if else conditions
You can validate your form this way.
function validate() {
var a = document.forms["Form"]["uname"].value;
var b = document.forms["Form"]["number"].value;
var c = document.forms["Form"]["mail"].value;
var validation=true;
if ((a == null || a == "")||(!a.match(/^([a-zA-Z]{2,30})$/))) {
document.getElementById('uname').className = 'box';
validation=false;
} else{
document.getElementById('uname').className = '';
}
if ((b == null || b == "")||(!b.match(/^\d*[0-9](|.\d*[0-9]|,\d*[0-9])?$/))) {
document.getElementById('mobNo').className = 'box';
validation=false;
} else{
document.getElementById('mobNo').className = '';
}
if ((c == null || c == "")||(!c.match(/^([\w-\.]+#([\w-]+)+(\.[\w-]{2,4})?)$/))) {
document.getElementById('mail').className = 'box';
validation=false;
}else{
document.getElementById('mobNo').className = '';
}
return validation;
}
Here is a working codepen link,
http://codepen.io/nadirlaskar/pen/rjOEJQ

in:
if (a==null || a=="",b==null || b=="",c==null || c=="")
, operator will do nothing; it returns last comparison:
(c==null || c=="")
please fix as
if ((a==null || a=="") && (b==null || b=="") && (c==null || c==""))

Related

Form cant progress any further and seems on getting stuck in function

when checking one of the language,degree or car options and fill out their corresponding inputs the form gets gets stuck on the Cage() function(it displays the message but doesnt progress further) and I dont know why any clues?I also find out by removing the upper functions (Cemail,Cuser,Checkpassword) one by one that they all get stuck and don't let the button get enabled.Is it because too many boolean functions are in the enableMe() if?
I am a student and still learning so, sorry for the headache in advance.
function Cuser() {
var Us = document.getElementById("User").value;
if (Us.length < 7 || Us.length > 15) {
l1.innerHTML = "The username must be at least 7 characters and up to 15";
return false;
}
else if (Us == "" || Us == " " || Us == " " || Us == " " || Us == null) {
l1.innerHTML = "The username must be filled with at least 7 characters";
return false;
}
else {
l1.innerHTML = "Username is Valid";
return true
}
}
function Cemail() {
var Em = document.getElementById("mail").value;
var patt = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/;
if (Em == "" || Em == " " || Em == " " || Em == " " || Em == null) {
l1.innerHTML = "Please fill out the email";
return false;
}
else if (!patt.test(Em)) {
l1.innerHTML = "Please fill out the email correctly";
return false;
}
else {
l1.innerHTML = "email is valid";
return true;
}
}
function CheckPassword() {
var p = document.getElementById("pass1").value;
var p1 = document.getElementById("pass2").value;
var pattent = /[A-Z]/;
if (p == "" || p == " " || p == " " || p == " " || p == null) {
l1.innerHTML = "The password must be filled with at least 6 characters";
return false;
}
else if (p.length < 6 || p1.length > 12) {
l1.innerHTML = "Password min chars:6 Max chars:12";
return false;
}
else if (!p.match(pattent)) {
l1.innerHTML = "please include at least one capital letter"
return false;
}
else if (p1 != p) {
l1.innerHTML = "Passwords must be identical.";
return false;
}
else {
l1.innerHTML = "password is valid";
return true;
}
}
function checkPasswordStrenght() {
var x = document.getElementById("pass1").value;
if (x.length == 6) {
document.getElementById("strenght").value = "0";
}
if (x.length == 7) {
document.getElementById("strenght").value = "15";
}
if (x.length == 8) {
document.getElementById("strenght").value = "30";
}
if (x.length == 9) {
document.getElementById("strenght").value = "45";
}
if (x.length == 10) {
document.getElementById("strenght").value = "65";
}
if (x.length == 11) {
document.getElementById("strenght").value = "80";
}
if (x.length == 12) {
document.getElementById("strenght").value = "100";
}
}
function Cage() {
var Ag = document.getElementById("Age").value;
if (isNaN(Ag) == true || Ag == " " || Ag == "" || Ag == " ") {
l1.innerHTML = "Age must be a number.";
return false;
}
else if (Ag < 18) {
l1.innerHTML = "You must be an Adult to use this form";
return false;
}
else {
l1.innerHTML = "Age is valid";
return true;
}
}
function DisableMe() {
document.getElementById("butt").disabled = true;
}
function myCar() {
var checkBox = document.getElementById("myCheck");
var text = document.getElementById("text");
if (checkBox.checked == true) {
text.style.display = "block";
} else {
text.style.display = "none";
}
}
function myDegree() {
var checkBox = document.getElementById("myDeg");
var text = document.getElementById("Ddeg");
if (checkBox.checked == true) {
text.style.display = "block";
} else {
text.style.display = "none";
}
}
function myLangu() {
var checkBox = document.getElementById("myLang");
var text = document.getElementById("Llang");
if (checkBox.checked == true) {
text.style.display = "block";
} else {
text.style.display = "none";
}
}
function Checker() {
if (document.getElementById("GF").checked == false && document.getElementById("GM").checked == false) {
l1.innerHTML = "Please select your gender";
return false;
}
else {
return true;
}
}
function CChecker() {
var Cheddar = document.getElementById("myCheck").checked;
var Ham = document.getElementById("TypeOfCar").value;
if (Cheddar == true) {
if (Ham == "" || Ham == " " || Ham == " " || Ham == " " || Ham == null) {
l1.innerHTML = "Please Fill in the type of car you own";
}
}
else {
return true;
}
}
function LChecker() {
var Lettuce = document.getElementById("myLang").checked;
var Tomato = document.getElementById("TypeOfLang").value;
if (Lettuce == true) {
if (Tomato == "" || Tomato == " " || Tomato == " " || Tomato == " " || Tomato == null) {
l1.innerHTML = "Please Fill in at least one foreign language that you know";
}
}
else {
return true;
}
}
function DChecker() {
var Bread = document.getElementById("myDeg").checked;
var Mayo = document.getElementById("TypeOfDeg").value;
if (Bread == true) {
if (Mayo == "" || Mayo == " " || Mayo == " " || Mayo == " " || Mayo == null) {
l1.innerHTML = "Please Fill in at least one degree you own";
}
}
else {
return true;
}
}
function enableMe() {
if (Cuser() && Cemail && CheckPassword && Cage() && Checker() && CChecker() && LChecker() && DChecker()) {
document.getElementById("butt").disabled = false;
l1.innerHTML = "All credentials are valid";
return true;
}
else {
document.getElementById("butt").disabled = true;
}
}
<!DOCTYPE html>
<html>
<head>
<link rel="shortcut icon" type="image/x-icon" href="favicon.ico" />
<meta name="description" content="Form signup and php">
<meta name="keywords" content="Signup,html,php,react">
<meta name="author" content="Filippos Karagiannis">
<link href="StyleSheet.css" rel="stylesheet" />
<title>Exclusive Signup</title>
<script src="JavaScript.js"></script>
</head>
<body style="background-color:powderblue; text-align:center;" onload="DisableMe()">
<center>
<form action="react.html" display: inline - block;">
<fieldset class="center" style="width:50%; font-size:x-large; color:#383838;font-family:'Trebuchet MS', 'Lucida Sans Unicode', 'Lucida Grande', 'Lucida Sans', Arial, sans-serif">
<legend><b>Sign up form</b></legend>
<p>
<input type="text" id="User" name="Username" onchange="return Cuser()" placeholder="Type Username" />
</p>
<p>
<input type="email" id="mail" name="Email" onchange="return Cemail()" placeholder="e-Mail" />
</p>
<p>
<input type="password" id="pass1" name="Pass1"
placeholder="Password" onkeyup="checkPasswordStrenght(pass1), CheckPassword()" />
<input type="password" id="pass2" name="Pass2"
placeholder="Confirm Password" />
</p>
<div class="Strng">Password strenght:</div> <progress max="100" value="0" id="strenght" style="width:230px"></progress>
<p> <input type="text" id="Age" onchange="return Cage()" name="Age" placeholder="Type Age" /> </p>
<div class="Strng">
Male<input type="radio" id="GM" name="gender" value="male">
<input type="radio" id="GF" name="gender" value="female"> Female
</div>
<div class=" Strng">Do you own a car?<input type="checkbox" id="myCheck" onclick="myCar()"></div>
<div id="text" style="display:none"><input type="text" id="TypeOfCar" placeholder="Please inlcude the type of car" /></div>
<div class=" Strng">Do you know any other Languages<input type="checkbox" id="myLang" onclick="myLangu()"></div>
<div id="Llang" style="display:none"><input type="text" id="TypeOfLang" placeholder="Please inlcude the Languages" /></div>
<div class=" Strng">Do you own any postgraduate degrees<input type="checkbox" id="myDeg" onclick="myDegree()"></div>
<div id="Ddeg" style="display:none"><input type="text" id="TypeOfDeg" placeholder="Please inlcude the type of Degrees" /></div>
<p><div onmouseover="return enableMe()">Click Bellow to register your credentials</div></p>
<div onmouseover="return enableMe()">
<input class="button" id="butt" type="submit" value="Register">
</div>
<label class="Labbel" id="l1"></label>
</fieldset>
</form>
</center>
</body>
</html>
As well as some syntax errors Burham mentions in the comments.
Why the button won't enable is due to your CChecker(), LChecker() and DChecker() functions, you never return true if one is selected and a value is filled.
Example of where to add return (view comment, add to other functions in same place):
function CChecker() {
var Cheddar = document.getElementById("myCheck").checked;
var Ham = document.getElementById("TypeOfCar").value;
if (Cheddar == true) {
if (Ham == "" || Ham == " " || Ham == " " || Ham == " " || Ham == null) {
l1.innerHTML = "Please Fill in the type of car you own";
}
// else return true
else {
return true;
}
}
else {
return true;
}
}

Javascript form validation. No error message. No popup

I need some help getting JS form validation working.
I have form rules in a .js script file I've linked to in the html head.
Example of for rule:
function IsValid4DigitZip( str ) {
// Return immediately if an invalid value was passed in
if (str+"" == "undefined" || str+"" == "null" || str+"" == "")
return false;
var isValid = true;
str += "";
// Rules: zipstr must be 5 characters long, and can only contain numbers from
// 0 through 9
if (IsBlank(str) || (str.length != 4) || !IsInt(str, false))
isValid = false;
return isValid;
} // end IsValid4DigitZip
This is my html:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>orderbooks</title>
<link rel="stylesheet" href="styles.css">
<script src="datavalidation.js"></script>
<script type="text/javaScript">
function validate(orderbooks){
var digits="0123456789"
var temp
if ( IsValid4DigitZip(document.orderbooks.Postcode.value) ) {
// Zip code is valid
} else {
alert("Invalid postcode:)
// Zip code is invalid
}
return true
}
</script>
</head>
<body>
<form name="orderbooks" onSubmit="return validate(orderbooks)" >
Name: <input type="text" size="20" name="Name">
Street Number: <input type="text" size="5" name="streetnumber" maxlength="5">
Street Name: <input type="text" size="20" name="streetname" maxlength="25">
Postcode: <input type="text" size="4" name="postcode" maxlength="4">
Telephone: <input type="text" size="11" name="telephone" maxlength="11">
Email: <input type="text" size="20" name="email" maxlength="50">
<input type="reset" value="Clear the Form">
<input type="submit" value="Submit Form">
</form>
</body>
</html>
What am I doing wrong? I can't get it to show the alert or warning.
OK I got the postcode to work with a error message! I have another question.
If I wanted to add this form validation rule:
function IsNum( numstr ) {
// Return immediately if an invalid value was passed in
if (numstr+"" == "undefined" || numstr+"" == "null" || numstr+"" == "")
return false;
var isValid = true;
var decCount = 0; // number of decimal points in the string
// convert to a string for performing string comparisons.
numstr += "";
// Loop through string and test each character. If any
// character is not a number, return a false result.
// Include special cases for negative numbers (first char == '-')
// and a single decimal point (any one char in string == '.').
for (i = 0; i < numstr.length; i++) {
// track number of decimal points
if (numstr.charAt(i) == ".")
decCount++;
if (!((numstr.charAt(i) >= "0") && (numstr.charAt(i) <= "9") ||
(numstr.charAt(i) == "-") || (numstr.charAt(i) == "."))) {
isValid = false;
break;
} else if ((numstr.charAt(i) == "-" && i != 0) ||
(numstr.charAt(i) == "." && numstr.length == 1) ||
(numstr.charAt(i) == "." && decCount > 1)) {
isValid = false;
break;
}
//if (!((numstr.charAt(i) >= "0") && (numstr.charAt(i) <= "9")) ||
} // END for
return isValid;
} // end IsNum
Would I add it by typing this in the html directly under the first function rule:
if (IsNum(document.orderbooks.querySelectorAll("[name=postcode]")[0].value)) {
// Zip code is valid
} else {
alert("Postcode invalid! Please use only numbers:");
return false;
}
Is that how I would do this?
Two issues in your code:
Alert is missing double quotes.
The postcode value sent to IsValid4DigitZip is wrong.
Replace
document.orderbooks.Postcode.value
with
document.orderbooks.querySelectorAll("[name=postcode]")[0].value
Updated validate function code:
function validate(orderbooks) {
var digits = "0123456789"
var temp
if (IsValid4DigitZip(document.orderbooks.querySelectorAll("[name=postcode]")[0].value)) {
// Zip code is valid
} else {
alert("Invalid postcode:");
return false;
}
return true
}
function validate(orderbooks) {
var digits = "0123456789"
var temp
if (IsValid4DigitZip(document.orderbooks.querySelectorAll("[name=postcode]")[0].value)) {
// Zip code is valid
} else {
alert("Invalid postcode:");
return false;
}
return true
}
function IsValid4DigitZip(str) {
// Return immediately if an invalid value was passed in
if (str + "" == "undefined" || str + "" == "null" || str + "" == "")
return false;
var isValid = true;
str += "";
// Rules: zipstr must be 5 characters long, and can only contain numbers from
// 0 through 9
if ((str.trim().length != 4) || !isNumeric(str.trim()))
isValid = false;
return isValid;
} // end IsValid4DigitZip
//Check for numbers
function isNumeric(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
<form name="orderbooks" onSubmit="return validate(orderbooks)">
Name: <input type="text" size="20" name="Name"> Street Number: <input type="text" size="5" name="streetnumber" maxlength="5"> Street Name: <input type="text" size="20" name="streetname" maxlength="25"> Postcode: <input type="text" size="4" name="postcode"
maxlength="4"> Telephone: <input type="text" size="11" name="telephone" maxlength="11"> Email: <input type="text" size="20"
name="email" maxlength="50">
<input type="reset" value="Clear the Form">
<input type="submit" value="Submit Form">
</form>

Very strange javascript issue with booleans

Booleans will work before setting variables inside a function but not after? The variables are all taken from forms except "status".
Here is the function:
<script src="js/main.js"></script>
<script src="js/ajax.js"></script>
<script>
function signup(){
// if(1==1){ -----When I place this here, the alert comes up.
// alert("yes");
// }
var u = _("username").value;
var e = _("email").value;
var p1 = _("pass1").value;
var p2 = _("pass2").value;
var c = _("country").value;
var g = _("gender").value;
var a = _("age").value;
var o = _("occ").value;
var status = _("status");
// Nothing below here works
if(u == "" || e == "" || p1 == "" || p2 == "" || c == "" || g == "" || a == "" || o == ""){
status.innerHTML = "Fill out all of the form data";
alert("true");
} else if(p1 != p2){
status.innerHTML = "Your password fields do not match";
}
else if( _("terms").style.display == "none"){
status.innerHTML = "Please view the terms of use";
} else {
_("signupbtn").style.display = "none";
status.innerHTML = 'please wait ...';
var ajax = ajaxObj("POST", "signupfront.php");
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true) {
if(ajax.responseText != "signup_success"){
status.innerHTML = ajax.responseText;
_("signupbtn").style.display = "block";
} else {
window.scrollTo(0,0);
_("signupform").innerHTML = "OK "+u+", check your email inbox and junk mail box at <u>"+e+"</u> in a moment to complete the sign up process by activating your account. You will not be able to do anything on the site until you successfully activate your account.";
}
}
}
ajax.send("u="+u+"&e="+e+"&p="+p1+"&c="+c+"&g="+g+"&a="+a+"&o="+o);
}
}
This function is called by a button, and I want the function to return the messages alongside the button.
<button id="signupbtn" onclick="signup()">Create Account</button>
<span id="status"></span>
main.js contains the following:
function _(x){
return document.getElementById(x);
}
Any help with this would be greatly appreciated as I have been looking at it for hours and cannot figure it out.
Thanks in advance
Here is the html as requested:
<body>
<div id="pageMiddle">
<h3>Create Account</h3>
<form name="signupform" id="signupform" onsubmit="return false;">
<div>Username: </div>
<input id="username" type="text" onblur="checkusername()" onkeyup="restrict('username')" maxlength="16">
<span id="unamestatus"></span>
<div>Email Address:</div>
<input id="email" type="text" onfocus="emptyElement('status')" onkeyup="restrict('email')" maxlength="88">
<div>Create Password:</div>
<input id="pass1" type="password" onfocus="emptyElement('status')" maxlength="16">
<div>Confirm Password:</div>
<input id="pass2" type="password" onfocus="emptyElement('status')" maxlength="16">
<div>Age:</div>
<input id="age" type="text" onfocus="emptyElement('status')" maxlength="3">
<div>Occupation:</div>
<input id="occ" type="text" onfocus="emptyElement('status')" maxlength="88">
<div>Gender:</div>
<input type="radio" name="gender" value="m">Male
<input type="radio" name="gender" value="f">Female
<div>Country:</div>
<select id="country" onfocus="emptyElement('status')">
//long list of countries here
</select>
<div>
<a href="#" onclick="return false" onmousedown="openTerms()">
View the Terms Of Use
</a>
</div>
<div id="terms" style="display:none;">
<h3>Our Terms Of Use</h3>
<p>v</p>
</div>
<br /><br />
<button id="signupbtn" onclick="signup()">Create Account</button>
<span id="status"></span>
</form>
</div>
</body>
if any of your input fields that you are referencing in the variable declaration do not exist your code will fail, because you are calling .value on an undefined field.
post your HTML and we can figure it out.
Have a look at the gender input
<div>Gender:</div>
<input type="radio" name="gender" value="m">Male
<input type="radio" name="gender" value="f">Female
Here's your mistake
var g = _("gender").value;
The code breaks at the above line because you're trying to get the value of an element with id equals gender, but there's no element with id="gender" attribute.
You need to change the gender input to the following, where the radio buttons have the unique id (genderMale and genderFemale)
<div>Gender:</div>
<input type="radio" name="gender" id="genderMale" value="m">Male
<input type="radio" name="gender" id="genderFemale" value="f">Female
then use the following syntax to assign the value of the selected gender to g variable
var g = "";
if (document.getElementById("genderMale").checked) {
g = _("genderMale").value;
} else if (document.getElementById("genderFemale").checked) {
g = _("genderFemale").value;
}
Below is the modified part of the javascript
var u = _("username").value;
var e = _("email").value;
var p1 = _("pass1").value;
var p2 = _("pass2").value;
var c = _("country").value;
var a = _("age").value;
var o = _("occ").value;
var status = _("status");
var g = "";
if (document.getElementById("genderMale").checked) {
g = _("genderMale").value;
} else if (document.getElementById("genderFemale").checked) {
g = _("genderFemale").value;
}
if (u == "" || e == "" || p1 == "" || p2 == "" || c == "" || g == "" || a == ""
|| o == "") {
status.innerHTML = "Fill out all of the form data";
alert("true");
}
Demo: http://jsfiddle.net/zpeu4fq9/1/
Try using this
if(1===1){
alert("yes");
}
if(u === "" || e === "" || p1 === "" || p2 === "" || c === "" || g === "" || a === "" || o === ""){
status.innerHTML = "Fill out all of the form data";
alert("true");
} else if(p1 != p2){
status.innerHTML = "Your password fields do not match";
}
Hope this help

Problems with form validations

<div id="form">
<form method="post" action="register1.aspx" onsubmit="return validateForm();"name="register1" >
<h1>
Register to exess the site</h1>
<input type="text" name="firstname" class=" br"/>
<em>First name</em><br />
<span id="firstnmsg"></span><br />
<input type="text" name="lastname" class=" br" /><em>Last name</em><br />
<span id="lastnmsg"></span><br />
<input type="text" name="username" class=" br" /><em>username</em><br>
<span id="usermsg"></span><br />
<input type="password" name="password" class=" br" /><em>password</em><br />
<input type="password"name="password1" class=" br" /><em>Confirm password</em>
<span id="pass1msg"></span><br />
<input type="text" name="email" class=" br"/><em>Email!</em><br />
<span id="emailmsg"></span><br />
<select name="sex">
<option>Please select a Gender</option>
<option>Male</option>
<option>Female</option>
<em>Gender</em>
</select><br />
<input type="submit" name="submit" value="Register " onclick="return validateForm();" />
<input type="reset" name="reset" value="Reset" onclick="return resetMsg();"/>
</form>
<span> <%=Session["regstatus"] %></span>
</div>
<div id="log_in">
<h1><em>log in</em></h1>
<form action="WebForm2.aspx"method="post" name="log_in" onsubmit="return validateloginform"><br />
<span id="usernamemsg"><%=Session["usernamemsg"] %> </span><input type="text" name="username_1" class="br" /><em>Username</em><br />
<span id="passwordmsg"><%=Session ["passwordmsg"] %></span><input type="password" name="password_1" class="br" /><em>Password</em><br />
<input type="submit" name="submit2" onclick=" validateloginform"/>
</form>
</div>
<script type="text/javascript">
function isEmpty(str) {
return (str.length == 0);
}
function isNumeric(str) {
var c = true;
for (var i = 0; i < str.length; i++) {
c = !(isNaN(str[i]));
}
return c;
}
function isValid(str) {
var badChar = "\\;:!##$%^&*()-_=+`~<>?[]{}|/,.";
for (var l = 0; l < str.length; l++) {
for (var c = 0; c < badChar.length; c++) {
if (str[l] == badChar[c]) {
return true;
}
if (str[l] == " " || str[l] == "\"" || str[l] == "\'") {
return true;
}
}
}
return false;
}
function isShort(str) {
return (str.length < 3);
}
//Reset Error Messages Function -->
function resetMsg() {
document.getElementById("firstnmsg").innerHTML = "";
document.getElementById("lastnmsg").innerHTML = "";
document.getElementById("usermsg").innerHTML = "";
document.getElementById("passwordmsg").innerHTML = "";
document.getElementById("pssword1msg").innerHTML = "";
document.getElementById("emailmsg").innerHTML = "";
document.getElementById("BdateMsg").innerHTML = "";
document.getElementById("UnameMsg").innerHTML = "";
document.getElementById("PwdMsg").innerHTML = "";
document.getElementById("LoginError").innerHTML = "";
return true;
}
//Main Sign Up Form Validation Function -->
function validateForm() {
resetMsg();
var val = true;
//First Name Validation ---------------------------------------->
if (isEmpty(register1.firstname.value)) {
document.getElementById("firstnmsg").innerHTML = " Empty";
val = false;
}
else {
if (isNumeric(register1.firstname.value) || isValid(signup.firstname.value)) {
document.getElementById("firstnmsg").innerHTML = " Letters Only";
val = false;
}
else {
if (isShort(register1.firstname.value)) {
document.getElementById("firstnmsg").innerHTML = " Too Short";
val = false;
}
}
}
//Last Name Validation ------------------>
if (isEmpty(register1.lastname.value)) {
document.getElementById("lastnmsg").innerHTML = " Empty";
val = false;
}
else {
if (isNumeric(register1.lastname.value) || isValid(signup.lastname.value)) {
document.getElementById("lastnmsg").innerHTML = " Letters Only";
val = false;
}
else {
if (isShort(register1.lastname.value)) {
document.getElementById("lastnmsg").innerHTML = " Too Short";
val = false;
}
}
}
//Username Validation --------------------------------------------->
if (isEmpty(register1.username.value)) {
document.getElementById("usermsg").innerHTML = " Empty";
val = false;
}
else {
if (!isNumeric(register1.username.value)) {
document.getElementById("usermsg").innerHTML = " Use Numbers";
}
else {
if (isShort(register1.username.value)) {
document.getElementById("usermsg").innerHTML = " Too Short";
val = false;
}
}
}
//Password Validation ----------------------------------------------->
if (isEmpty(register1.password1.value)) {
document.getElementById("Password1Msg").innerHTML = " Empty";
val = false;
}
else {
if (isValid(register1.password.value)) {
document.getElementById("Password1Msg").innerHTML = " Invalid";
}
else {
if (register1.password.value == register1.password1.value) {
if (signup.password1.value.length < 6 && signup.password1.value != "") {
document.getElementById("pass1msg").innerHTML = " Too Short";
val = false;
}
}
else {
document.getElementById("pass1msg").innerHTML = " Don't Match";
val = false;
}
}
}
//Email Validation -------------------------------------->
var EmailField = document.forms["register1"]["email"].value;
var atpos = EmailField.indexOf("#");
var dotpos = EmailField.lastIndexOf(".");
if (atpos < 1 || dotpos < atpos + 2 || dotpos + 2 >= EmailField.length) {
document.getElementById("emailmsg").innerHTML = " Invalid Email";
val = false;
}
if (EmailField == null || EmailField == "") {
document.getElementById("emailmsg").innerHTML = " Empty";
val = false;
}
//Main Login Validation Function -->
function validateLoginForm() {
resetMsg();
var val = true;
//Username Validation
if (isEmpty(log_in.username.value)) {
document.getElementById("usernamemsg").innerHTML = " Empty";
val = false;
}
//Password Validation
if (isEmpty(log_in.password.value)) {
document.getElementById("passwordmsg").innerHTML = " Empty";
val = false;
}
return val;
}
</script>
The validations won't work and I dont know why. This is a school project.
my main problem is that the script isnt running when im submiting the form ,when there even some errors at the form(what the user submits) it still goes to the next page and no innerHtml massage is shown.
Here, I went through your code, refractored a lot of it, wrote out some comments on how to improve it.
What stops the form from submitting is returning false. You're returning a variable called val, and if there is an error that variable is set to false, thus returning false and preventing the form from submitting.
I recommend taking the JS and putting it in your text editor and reading through everything. You should learn a good bit.
Here it is: http://jsfiddle.net/2x5LU/
I just did first name cause I have to work now, but you should be able to work off of this.
function validateForm(){
resetMsg();
var val = true;
if(isEmpty(firstName.value)){
firstNameMsg = 'Empty';
val = false;
}else if(isNumeric(firstName.value)){
firstNameMsg = 'Letters Only';
val = false;
}else if(isShort(firstName.value)){
firstNameMsg = 'Too Short';
val = false;
}
return val;
}

On submit form, return false not working

When I submit the form I got an alert message. When I accept the alert it will submit the form anyway. Returning false is ignored.
Onclick can not be used. I try with var x = document.forms["form"]["fname"].value;
and still same.
<form id="f" method="post" name="form" onsubmit="return validateForm();" action="#">
<input type="text" name="fname" id="test" />
<input type="submit" value="submit"/>
</form>
<script type="text/javascript">
function validateForm() {
var x = document.getElementById('test').value;
if (x == null || x == 0 || x == "0") {
alert("Stop");
return false;
}
}
</script>
Instead of <input type="submit" value="submit"/> use <input type="button" value="Submit" onclick='validateForm()'/>.
In your JS:
<script type="text/javascript">
function validateForm() {
var x = document.getElementById('test').value;
if (x == null || x == 0 || x == "0") {
alert("Stop");
}
else
document.form.submit();
}
</script>
Give this script inside of head tag and check it.
<script type="text/javascript">
function validateForm() {
var x = document.getElementById('test').value;
if (x == null || x == 0 || x == "0") {
alert("Stop");
return false;
}
}
</script>

Categories