I am using javascript and ajax to validate a register form at the moment the function restrict(elem) and the function checkusername() seem to be working, the ajax is passing checkusername variable to PHP and this checks if the username exists and displays a message to me saying username taken or available but no other fields get validated, this is my javascript
javascript validation clientside b4 going to php
function restrict(elem) {
var tf = _(elem);
var rx = new RegExp;
if (elem === "email") {
rx = /[' "]/gi;
} else if (elem === "username") {
rx = /[^a-z0-9]/gi;
} else if (elem === "mobileNumber") {
rx = /[0-9]/g;
}
tf.value = tf.value.replace(rx, "");
}
function emptyElement(x) {
_(x).innerHTML = "";
}
function checkusername() {
var u = _("username").value;
if (u !== "") {
_("unamestatus").innerHTML = 'checking ...';
var ajax = ajaxObj("POST", "signup.php");
ajax.onreadystatechange = function () {
if (ajaxReturn(ajax) === true) {
_("unamestatus").innerHTML = ajax.responseText;
}
};
ajax.send("usernamecheck=" + u);
}
}
function signup() {
var u = _("username").value;
var e = _("email").value;
var m = _("mobileNumber").value;
var p1 = _("pass1").value;
var p2 = _("pass2").value;
var ci = _("city").value;
var pc = _("postcode").value;
var c = _("country").value;
var d = _("dateOfBirth").value;
var g = _("gender").value;
var status = _("status");
if (u === "" || e === "" || p1 === "" || p2 === "" || c === "" || g === "" || m === "" || ci === "" || pc === "" || d === "") {
status.innerHTML = "Fill out required fields";
} else if (p1 !== p2) {
status.innerHTML = "Your password fields do not match";
} else if (m !== 11 && !IsNumeric(m)) {
status.innerHTML = "Please enter valid mobile number";
} else if (d === "dd/mm/yyyy") {
status.innerHTML = "Please enter your date of birth";
} else {
//ajax to send form data to php
//hides sign button
_("signupbtn").style.display = "none";
status.innerHTML = 'please wait ...';
//wait until php verifies data
var ajax = ajaxObj("POST", "signup.php");
ajax.onreadystatechange = function () {
if (ajaxReturn(ajax) === true) {
//if sign not succesful unhide button
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 + "&ci" + ci + "&m" + m + "&pc" + pc + "&d" + d);
}
}
and here is my form
<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="email" 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>First name:</div>
<input id="firstName" type="text" /><br />
<div>Last name:</div>
<input id="lastName" type="text" /><br />
<div>Mobile number*:</div>
<input name="mobileNumber" onfocus="emptyElement('status')" onkeyup="restrict('mobileNumber')" maxlength="16">
<div>Gender:</div>
<select id="gender" onfocus="emptyElement('status')">
<option value=""></option>
<option value="Male">Male</option>
<option value="Female">Female</option>
</select>
<div>Country:</div>
<select id="country" onfocus="emptyElement('status')">
<?php include_once("country_list.php"); ?>
</select>
<div>City:</div>
<input id="city" onfocus="emptyElement('status')">
<div>Postcode:</div>
<input id="postcode" onfocus="emptyElement('status')">
<div>Relationship Status*:</div>
<select id="relationshipStatus" >
<option value=""></option>
<option value="Single">Single</option>
<option value="Taken">Taken</option>
</select>
<div>Date of Birth*:</div>
<input id="dateOfBirth" type="date" onfocus="emptyElement('status')">
<button id="signupbtn" onclick="signup()">Create Account</button>
<span id="status"></span>
</form>
Your validation regular expressions won't do what you want:
function restrict(elem) {
var tf = _(elem);
var rx = new RegExp;
if (elem === "email") {
rx = /[' "]/gi;
} else if (elem === "username") {
rx = /[^a-z0-9]/gi;
} else if (elem === "mobileNumber") {
rx = /[0-9]/g;
}
tf.value = tf.value.replace(rx, "");
}
Your expression are set up so that they'll pass validation if any single character in the field value matches the character range. You can stipulate that an entire string consist of characters from a particular range like this:
rx = /^[a-z0-9]*$/;
Related
New to JS, need to swap the 2 non-whitespace input values (text) with each other via button. This is what I've tried:
function switcher() {
var f = document.getElementById('inp').value;
var s = document.getElementById('inp2').value;
[f, s] = [s, f];
if (f === '' || f === ' ', s === '' || s === ' ') {
alert("fill a blank!");
} else if (f !== '' || f !== ' ', s !== '' || s !== ' ') {
f = s;
s = f;
}
}
<input type="text" id="inp" value="" size="50">
<input type="button" id="btn" value="Поменять местами" onclick="switcher()">
<input type="text" id="inp2" value="" size="50">
Here would be my solution:
function switcher() {
const input1 = document.getElementById('input1');
const input2 = document.getElementById('input2');
const text1 = input1.value
const text2 = input2.value
if (isStringEmpty(text1) || isStringEmpty(text2)) return alert("fill a blank!")
input1.value = text2
input2.value = text1
}
function isStringEmpty(string) {
return !string.trim().length
}
<input required type="text" id="input1" value="" size="50" />
<input type="button" id="btn" value="Поменять местами" onclick="switcher()" />
<input required type="text" id="input2" value="" size="50" />
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;
}
}
My html code sends the request to php to send email. In my case the email can be sent in Google Chrome & Edge but not in Firefox when I set the button type=submit, when I change type=button, it works fine. My javascript code is:
function Send() {
var allset = true;
var namevalid = true;
var emailvalid = false;
var commentvalid = false;
var sent = 0;
var emailPattern = /^[a-zA-Z0-9._-]+#[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
if ($("#email").val() == '' || $("#email").val() == null) {
$("#email").addClass("invalid");
allset = false;
}
else {
if (!$("#email").val().match(emailPattern)) {
$("#email").removeClass("valid");
$("#email").addClass("invalid");
allset = false;
}
else {
emailvalid = true;
$("#email").addClass("valid");
}
}
if ($("#comment").val() == '' || $("#comment").val() == null) {
$("#comment").addClass("invalid");
allset = false;
}
else {
commentvalid = true;
$("#comment").addClass("valid");
}
$("#name").addClass("valid");
if (namevalid === true && emailvalid === true && commentvalid === true) {
var name = document.getElementById("name").value;
var email = document.getElementById("email").value;
var number = document.getElementById("number").value;
var demo = document.getElementById("sel1").value;
var comment = document.getElementById("comment").value;
alert("Request Successfully Received");
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if (xhttp.readyState == 4 && xhttp.status == 200) {
alert(xhttp.responseText)
}
};
sent = 1;
xhttp.open("POST", "email.php?" + "name=" + name + "&mail=" + email + "&phone=" + number + "&msg=" + comment + "&demo=" + demo, true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send();
}
else
{
alert("Please fill all the fields correctly");
}
}
My html for form's button is:
<form class="form" id="form1">
<p class="name">
<input name="name" type="text" class="validate[required,custom[onlyLetter],length[0,100]] feedback-input" placeholder="Name" id="name" />
</p>
<p class="email">
<input name="email" type="text" class="validate[required,custom[email]] feedback-input" id="email" placeholder="Email" />
</p>
<p class="number">
<input type="text" name="telephone" maxlength="30" class="feedback-input" size="30" id="number" placeholder="Number">
</p>
<p class="number" id="demotype">
<select class="form-control feedback-input demotype" id="sel1" name="demo">
<option> something </option>
</select>
</p>
<p class="text">
<textarea name="text" class="validate[required,length[6,300]] feedback-input" id="comment" placeholder="Comment"></textarea>
</p>
<div class="submit">
<input type="submit" id="button-blue" onclick="Send()" value="Send" />
<div class="ease"></div>
</div>
</form>
'type=submit' is basically for submitting forms and 'type=button' is just a button to be bind with some functions. If you don't have any form as its parent element and an error occurs when you click the button, I suggest you to use 'type=button' instead.
Just add return false; at the end of function becuase submit button submits your form. Like this.
function Send() {
var allset = true;
var namevalid = true;
var emailvalid = false;
var commentvalid = false;
var sent=0;
var emailPattern = /^[a-zA-Z0-9._-]+#[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
if ($("#email").val() == '' || $("#email").val() == null) {
$("#email").addClass("invalid");
allset = false;
}
else {
if (!$("#email").val().match(emailPattern)) {
$("#email").removeClass("valid");
$("#email").addClass("invalid");
allset = false;
}
else {
emailvalid = true;
$("#email").addClass("valid");
}
}
if ($("#comment").val() == '' || $("#comment").val() == null) {
$("#comment").addClass("invalid");
allset = false;
}
else {
commentvalid = true;
$("#comment").addClass("valid");
}
$("#name").addClass("valid");
if (namevalid === true && emailvalid === true && commentvalid === true) {
var name = document.getElementById("name").value;
var email = document.getElementById("email").value;
var number = document.getElementById("number").value;
var demo=document.getElementById("sel1").value;
var comment = document.getElementById("comment").value;
alert("Request Successfully Received");
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
alert(xhttp.responseText)
}
};
sent=1;
xhttp.open("POST", "email.php?"+"name="+name+"&mail="+email+"&phone="+number+"&msg="+comment+"&demo="+demo, true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send();
}
else
{
alert("Please fill all the fields correctly");
}
return false;
}
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
<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;
}