<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;
}
Related
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;
}
}
Hi guys i have a problem with my code
my code is showing message for password input instead of email input message, while im typing in email input
can u help me?
var emInpVal = document.getElementById('emIn');
var psInpVal = document.getElementById('psIn');
var msg = "";
function realTime(){
var loginBtn = document.getElementById('login');
if(emInpVal.value.length <= 5){
msg = "Adres e-mail zbyt krótki.";
loginBtn.disabled = true;
loginBtn.style.backgroundColor = "red";
}
else if(emInpVal.value.length > 5) {
msg = "";
loginBtn.disabled = false;
loginBtn.style.backgroundColor = '#157e79';
}
if(psInpVal.value.length <= 6){
msg = "Hasło musi mieć conajmniej 6 znaków";
loginBtn.disabled = true;
loginBtn.style.backgroundColor = "red";
}
else if(psInpVal.value.length > 6){
msg = "";
loginBtn.disabled = false;
loginBtn.style.backgroundColor = '#157e79';
}
document.getElementById('span').innerHTML = msg;
};
<div id="wrap">
<div class="frame">
<h1>Login here</h1>
<h3>You have account already? Click sign in</h3>
<form id="forma">
<input type="email" id="emIn" name="emailInput" placeholder="Email adress" onkeyup="realTime(this)" required>
<input type="password" id="psIn" name="passwordInput" placeholder="Password" onkeyup="realTime(this)" required>
<input type="submit" name="signin" id="signIn" value="Sign in">
<input type="submit" name="login" id="login" value="Login">
<div class="bottomLink">
<h1>Forget password?</h1>
<span id="span"></span>
</div>
</form>
</div>
can't find resolve of problem, even if i put this. to element it's not showing the message
The first condition is doing right however the problem is that the second condition is executing just after the first condition even if the first condition meets the clause which means it is replacing the error message of the first condition. Below is the correct code.
function realTime() {
var emInpVal = document.getElementById('emIn');
var psInpVal = document.getElementById('psIn');
var msg = "";
var loginBtn = document.getElementById('login');
if (emInpVal.value.length <= 5) {
loginBtn.disabled = true;
loginBtn.style.backgroundColor = "red";
document.getElementById('span').innerHTML = "Adres e-mail zbyt krótki.";
return;
} else if (psInpVal.value.length <= 6) {
loginBtn.disabled = true;
loginBtn.style.backgroundColor = "red";
document.getElementById('span').innerHTML = "Hasło musi mieć conajmniej 6 znaków";
return;
} else {
msg = "";
loginBtn.disabled = false;
loginBtn.style.backgroundColor = '#157e79';
document.getElementById('span').innerHTML = "";
}
};
That's because all the validator will run whenever you fire the keyUp, To selectively run a particular validator, I have added an extra check with the id of the element which is triggering the realTime() function of yours.
var emInpVal = document.getElementById('emIn');
var psInpVal = document.getElementById('psIn');
var msg = "";
function realTime(elem){
var loginBtn = document.getElementById('login');
if(elem.id == 'emIn' && emInpVal.value.length <= 5){
msg = "Adres e-mail zbyt krótki.";
loginBtn.disabled = true;
loginBtn.style.backgroundColor = "red";
}
else if(elem.id == 'emIn' && emInpVal.value.length > 5) {
msg = "";
loginBtn.disabled = false;
loginBtn.style.backgroundColor = '#157e79';
}
if(elem.id == 'psIn' && psInpVal.value.length <= 6){
msg = "password should be greater than or equal to 6";
loginBtn.disabled = true;
loginBtn.style.backgroundColor = "red";
}
else if(elem.id == 'psIn' && psInpVal.value.length > 6){
msg = "";
loginBtn.disabled = false;
loginBtn.style.backgroundColor = '#157e79';
}
document.getElementById('span').innerHTML = msg;
};
<div id="wrap">
<div class="frame">
<h1>Login here</h1>
<h3>You have account already? Click sign in</h3>
<form id="forma">
<input type="email" id="emIn" name="emailInput" placeholder="Email adress" onkeyup="realTime(this)" required>
<input type="password" id="psIn" name="passwordInput" placeholder="Password" onkeyup="realTime(this)" required>
<input type="submit" name="signin" id="signIn" value="Sign in">
<input type="submit" name="login" id="login" value="Login">
<div class="bottomLink">
<h1>Forget password?</h1>
<span id="span"></span>
</div>
</form>
</div>
Ok i've found answer for that problem,
thank You guys for helping
second if needs add of &&
Now i have another problem when i fill both inputs, and disabled property turns false so every conditions are done, i want to delete value of first input (email) and nothing happens now, conditions aren't changing back to disabled = true, and message of short email value not showing..
function realTime(){
var emInpVal = document.getElementById('emIn');
var psInpVal = document.getElementById('psIn');
var msg = "";
var loginBtn = document.getElementById('login');
if(emInpVal.value.length <= 5){
msg = "Adres e-mail zbyt krótki.";
loginBtn.disabled = true;
loginBtn.style.backgroundColor = "red";
}
else if(emInpVal.value.length > 5){
msg = "";
loginBtn.disabled = false;
loginBtn.style.backgroundColor = "#157e79";
}
if(psInpVal.value.length > 0 && psInpVal.value.length <= 6){
msg = "Hasło jest za krótkie"
loginBtn.disabled = true;
loginBtn.style.backgroundColor = "red";
}
else if(psInpVal.value.length > 6){
msg = "";
loginBtn.disabled = false;
loginBtn.style.backgroundColor = '#157e79';
}
document.getElementById('span').innerHTML = msg;
};
I'm having trouble with my form validation logic in my year one Javascript project.
Specifically with my errors reporting with the events.
The page randomly refreshes when I'm testing for "no username entered" etc.
Some errors will display for a moment and disappear.
Any help would be much appreciated, and will contribute to fixing the overall problem.
<body onload="setup()">
<div class="container-fluid">
<div class="page-header" class = "row">
<div class="col-lg-12">
<img id="banner" src = "pictures/homepage/banner.jpg" width = "100%" height = "20%"></img>
</div>
<p id="charc">Charcoal</p>
</div>
<div class="butts">
<button onclick="dropdown()" class="button">Categories</button>
<button class="button">My Account</button>
<button class="button">Shopping Cart</button>
<button id="loggedIn-Out" class="button">Login/Register</button>
</div>
<div id="myDropDwn" class= "dropContent">
womens
mens
shoes
accessories
</div>
</div>
<div class="login-page" class="col-lg-6">
<div class="form">
<form id="logForm" class="login-form">
<input id="username" type="text" placeholder="Username">
<div id="login-user-error" class="errorReps"></div>
<input id="password" type="password" placeholder="Password">
<div id="login-pass-error" class="errorReps"></div>
<button onclick="loginUser()">Login</button>
<div id="login-error" class="errorReps"></div>
<p class="loginMessage"> Not Registered? Register
<br>
<br>
Logout
</form>
<form id="regForm" class="register-form">
<input id="newFName" type="text" placeholder="First Name">
<div id="reg-FName-error" class="errorReps"></div>
<input id="newLName" type="text" placeholder="Last Name">
<div id="reg-LName-error" class="errorReps"></div>
<input id="newUName" type="text" placeholder="Username">
<div id="reg-UName-error" class="errorReps"></div>
<input id="newPass" type="password" placeholder="Password">
<div id="reg-pass-error" class="errorReps"></div>
<div id="passStrength"></div>
<input id="newEmail" type="email" placeholder="Email">
<div id="reg-email-error" class="errorReps"></div>
<input id="newPhone" type="number" placeholder="Tel. Number">
<div id="reg-phone-error" class="errorReps"></div>
<button onclick="registerUser()">Create</button>
<p class="loginMessage"> Already Registered? Login
</form>
</div>
</div>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script>
$('.loginMessage a').click(function(){
$('form').animate({height:"toggle", opacity: "toggle"}, "slow");
});
</script>
<script>
// pre-coded users
var existingUsers =
[
{
firstname: "Gerry",
lastname: "Agnew",
username: "GerryA",
password: "password123",
email: "gerry#gmit.ie",
phone:"0833333333"
},
{
firstname: "Sean",
lastname: "Duignan",
username: "SeanD",
password: "password456",
email: "sean#gmit.ie",
phone:"0822222222"
},
{
firstname: "Michael",
lastname: "Duignan",
username: "MichaelD",
password: "password789",
email: "michael#gmit.ie",
phone:"0844444444"
}
]
//function setup()
//{
// setup functions
//}
function dropdown()
{
document.getElementById("myDropDwn").classList.toggle("show");
}
username.addEventListener('blur', logUserVerify, true);
password.addEventListener('blur', logPassVerify, true);
newFName.addEventListener('blur', fNameVerify, true);
newLName.addEventListener('blur', lNameVerify, true);
newUName.addEventListener('blur', regUserVerify, true);
newPass.addEventListener('blur', regPassVerify, true);
newEmail.addEventListener('blur', emailVerify, true);
newPhone.addEventListener('blur', phoneVerify, true);
function loginValidate()
{
if(username == "")
{
document.getElementById("login-user-error").innerHTML = "Username required";
//username.focus();
return false;
}
if(password == "")
{
document.getElementById("login-pass-error").innerHTML = "Password required";
password.focus();
return false;
}
}
function registerValidate()
{
if(registerFName == "")
{
document.getElementById("reg-FName-error").innerHTML = "First Name required";
newFName.focus();
return false;
}
if(registerLName == "")
{
document.getElementById("reg-LName-error").innerHTML = "Last Name required";
newLName.focus();
return false;
}
if(registerUName == "")
{
document.getElementById("reg-UName-error").innerHTML = "Username required";
newUName.focus();
return false;
}
if(registerUName.length < 8)
{
document.getElementById("reg-UName-error").innerHTML = "Username must be 8 characters or more";
newUName.focus();
return false;
}
if(registerPass == "")
{
document.getElementById("reg-pass-error").innerHTML = "Password required";
newPass.focus();
return false;
}
if(registerEmail == "")
{
document.getElementById("reg-email-error").innerHTML = "Email required";
newEmail.focus();
return false;
}
if(registerPhone == "")
{
document.getElementById("reg-phone-error").innerHTML = "Phone number required";
newPhone.focus();
return false;
}
}
// Event Functions
function logUserVerify()
{
if (username != "")
{
document.getElementById("login-user-error").innerHTML = "";
return true;
}
}
function logPassVerify()
{
if (password != "")
{
document.getElementById("login-pass-error").innerHTML = "";
return true;
}
}
function fNameVerify()
{
if (registerFName != "")
{
document.getElementById("login-FName-error").innerHTML = "";
return true;
}
}
function lNameVerify()
{
if (registerLName != "")
{
document.getElementById("login-LName-error").innerHTML = "";
return true;
}
}
function regUserVerify()
{
if (registerUName != "")
{
document.getElementById("login-UName-error").innerHTML = "";
return true;
}
if (registerUName > 8)
{
document.getElementById("login-UName-error").innerHTML = "";
return true;
}
}
function regPassVerify()
{
if (registerPass != "")
{
document.getElementById("login-pass-error").innerHTML = "";
return true;
}
}
function phoneVerify()
{
if (registerPhone != "")
{
document.getElementById("login-phone-error").innerHTML = "";
return true;
}
}
function emailVerify()
{
if (registerEmail != "")
{
document.getElementById("login-email-error").innerHTML = "";
return true;
}
}
// Login/Register Functions
function loginUser()
{
var username = document.getElementById("username").value;
var password = document.getElementById("password").value;
for (i = 0; i < existingUsers.length; i++)
{
if(username == existingUsers[i].username && password == existingUsers[i].password)
{
alert(username + " Is logged in");
document.getElementById("loggedIn-Out").innerHTML = username;
document.getElementById("login-user-error").innerHTML = "";
localStorage.user = username;
localStorage.pass = password;
return;
}
else if(username != existingUsers[i].username)
{
document.getElementById("login-user-error").innerHTML = "Invalid, user does not exist";
username.focus();
return false;
}
else
{
loginValidate();
}
}
}
function logoutUser()
{
localStorage.removeItem("user");
localStorage.removeItem("pass");
document.getElementById("loggedIn-Out").innerHTML = "Login/Register";
}
function registerUser()
{
var registerFName = document.getElementById("newFName").value;
var registerLName = document.getElementById("newLName").value;
var registerUName = document.getElementById("newUName").value;
var registerPass = document.getElementById("newPass").value;
var registerEmail = document.getElementById("newEmail").value;
var registerPhone = document.getElementById("newPhone").value;
localStorage.regFname = registerFName;
localStorage.regLname = registerLName;
localStorage.regUname = registerUName;
localStorage.regPass = registerPass;
localStorage.regMail = registerEmail;
localStorage.regPhone = registerPhone;
var newUser =
{
firstname: registerFName,
lastname: registerLName,
username: registerUName,
password: registerPass,
email: registerEmail,
phone: registerPhone
}
for(i = 0; i < existingUsers.length; i++)
{
if(registerUName == existingUsers[i].username)
{
document.getElementById("reg-UName-error").innerHTML = "Username already exists";
newUName.focus();
return false;
}
if(registerEmail == existingUsers[i].email)
{
document.getElementById("reg-email-error").innerHTML = "Email already exists";
newEmail.focus();
return false;
}
registerValidate();
}
existingUsers.push(newUser);
}
// Password Strength functions
function passwordStr()
{
var passValue = document.getElementById("newPass").value;
if(passValue.length >= 8 && passValue.length <= 10)
{
document.getElementById("passStrength").innerHTML = "Weak";
}
else if(passValue.length > 10 && passValue.length <= 16)
{
document.getElementById("passStrength").innerHTML = "Average";
document.getElementById("passStrength").style.color = "yellow";
}
else if(passValue.length > 16)
{
document.getElementById("passStrength").innerHTML = "Strong";
document.getElementById("passStrength").style.color = "green";
}
else
{
document.getElementById("passStrength").style.color = "red";
}
}
var passInput = document.getElementById("newPass");
passInput.addEventListener("input", passwordStr);
</script>
Add a type attribute to your login button. type="button"
<button type="button" onclick="loginUser()">Login</button>
Without specifying a type, the button will default to submit behavior. You seem to be handling the login without default form submission, so setting the type to button just changes it to a regular button hence no form submission.
Am a new JavaScript programmer and am trying to make a form validator using JavaScript but the error messages don't seem to be displaying if all the forms are not filled, that is if all are empty, only the name form error displays.
This is what I tried:
function myValidate() {
var x = document.forms["myform"]["name"].value;
var y = document.forms["myform"]["country"].value;
var z = document.forms["myform"]["occupation"].value;
var a = document.forms["myform"]["status"].value;
if (x == "null" || x == "") {
var b = document.getElementById("nameErr");
b.innerHTML = "Name Must Be Filled Out";
return false;
} else {
var b = document.getElementById("nameErr");
b.innerHTML = "";
return true;
}
if (y == "null" || y == "") {
var c = document.getElementById("countryErr");
c.innerHTML = "Country Must Be Filled Out";
return false;
} else {
var c = document.getElementById("countryErr");
c.innerHTML = "";
return true;
}
if (z == "null" || z == "") {
var d = document.getElementById("occupationErr");
d.innerHTML = "Occupation Must Be Filled Out";
return false;
} else {
var d = document.getElementById("occupationErr");
d.innerHTML = "";
return true;
}
if (a == "null" || a == "") {
var e = document.getElementById("statusErr");
e.innerHTML = "Status Must Be Filled Out";
return false;
} else {
var e = document.getElementById("statusErr");
e.innerHTML = "";
return true;
}
}
This is the JavaScript code.
<form action="process.php" method="post" onsubmit="return myValidate()" name="myform">
Name:
<input type="text" id="name" name="name">
<span id="nameErr"></span><br><br>
Country:
<input type="text" id="country" name="country">
<span id="countryErr"></span><br><br>
Occupation:
<input type="text" id="occupation" name="occupation">
<span id="occupationErr"></span><br><br>
Status:
<input type="text" id="status" name="status">
<span id="statusErr"></span><br><br>
<input type="submit" name="submit" value="Submit">
</form>
This is the HTML form.
Please help, Thanks
It seems you don't realize that calling return ends the function you are in. If the validation fails, you'll want to return false, but you do not want to return true until the end of the validation process.
Try:
function myValidate() {
var x = document.forms["myform"]["name"].value;
var y = document.forms["myform"]["country"].value;
var z = document.forms["myform"]["occupation"].value;
var a = document.forms["myform"]["status"].value;
var b = document.getElementById("nameErr");
var c = document.getElementById("countryErr");
var d = document.getElementById("occupationErr");
var e = document.getElementById("statusErr");
if (!x || x.length==0) {
b.innerHTML = "Name Must Be Filled Out";
return false;
} else {
b.innerHTML = "";
}
if (!y || y.length==0) {
c.innerHTML = "Country Must Be Filled Out";
return false;
} else {
c.innerHTML = "";
}
if (!z || z.length==0) {
d.innerHTML = "Occupation Must Be Filled Out";
return false;
} else {
d.innerHTML = "";
}
if (!a || a.length==0) {
e.innerHTML = "Status Must Be Filled Out";
return false;
} else {
e.innerHTML = "";
}
return true;
}
This will return the first error it comes across. If you want to check them all at once, you will need to store your true/false in a variable and hold off on any return calls until then end and call return theVariableName;
you can use a flag for save state :
http://jsfiddle.net/vEvT2/1/
var flag = true;
and change to false if find empty control
I have this form
<form name="exampleform" id="exampleform" action="example123.html" method="get">
<fieldset>
<legend>Creating The Querystring</legend>
<label for="name_1">Name:</label>
<input type="text" name="name1" id="name_1" tabindex="1" size="40" value="Test1" />
<br />
<br />
<input type="submit" id='view_1' value="Submit" tabindex="2" />
</fieldset>
<br />
<br />
<fieldset>
<legend>Creating The Querystring</legend>
<label for="name_2">Name:</label>
<input type="text" name="name2" id="name_2" tabindex="1" size="40" value="Test2" />
<br />
<br />
<input type="submit" id='view_2' value="Submit" tabindex="2" />
</fieldset>
</form>
When it submits to the next page I want to be able to get the query string for the button that was clicked and not see both strings when the page loads. The script that I am using on the receiving page is:
<script type="text/javascript">
document.write("Name: " + Request.QueryString("name1"));
document.write("Name: " + Request.QueryString("name2"));
</script>
and
/*TITLE: Client-Side Request Object for javascript by Andrew Urquhart (UK)
HOME: http://andrewu.co.uk/tools/request/
COPYRIGHT: You are free to use this script for any use you wish, the only
thing I ask you do is keep this copyright message intact with the script.
Please don't pass it off as your own work, but feel free to enhance it and send
me the updated version. Please don't redistribute - it makes it harder to distribute
new versions of the script. This script is provided as is, with no warranty of any
kind. Use it at your own risk.
VERSION: #1.41 2007-06-28 18:10 UTC*/
function RObj(ea) {
var LS = "";
var QS = new Object();
var un = "undefined";
var x = null; // On platforms that understand the 'undefined' keyword replace 'null' with 'undefined' for maximum ASP-like behaviour.
var f = "function";
var n = "number";
var r = "string";
var e1 = "ERROR: Index out of range in\r\nRequest.QueryString";
var e2 = "ERROR: Wrong number of arguments or invalid property assignment\r\nRequest.QueryString";
var e3 = "ERROR: Object doesn't support this property or method\r\nRequest.QueryString.Key";
var dU = window.decodeURIComponent ? 1 : 0;
function Err(arg) {
if (ea) {
alert("Request Object:\r\n" + arg);
}
}
function URID(t) {
var d = "";
if (t) {
for (var i = 0; i < t.length; ++i) {
var c = t.charAt(i);
d += (c == "+" ? " " : c);
}
}
return (dU ? decodeURIComponent(d) : unescape(d));
}
function OL(o) {
var l = 0;
for (var i in o) {
if (typeof o[i] != f) {
l++;
}
}
return l;
}
function AK(key) {
var auk = true;
for (var u in QS) {
if (typeof QS[u] != f && u.toString().toLowerCase() == key.toLowerCase()) {
auk = false;
return u;
}
}
if (auk) {
QS[key] = new Object();
QS[key].toString = function() {
return TS(QS[key]);
}
QS[key].Count = function() {
return OL(QS[key]);
}
QS[key].Count.toString = function() {
return OL(QS[key]).toString();
}
QS[key].Item = function(e) {
if (typeof e == un) {
return QS[key];
}
else {
if (typeof e == n) {
var a = QS[key][Math.ceil(e)];
if (typeof a == un) {
Err(e1 + "(\"" + key + "\").Item(" + e + ")");
}
return a;
}
else {
Err("ERROR: Expecting numeric input in\r\nRequest.QueryString(\"" + key + "\").Item(\"" + e + "\")");
}
}
}
QS[key].Item.toString = function(e) {
if (typeof e == un) {
return QS[key].toString();
}
else {
var a = QS[key][e];
if (typeof a == un) {
Err(e1 + "(\"" + key + "\").Item(" + e + ")");
}
return a.toString();
}
}
QS[key].Key = function(e) {
var t = typeof e;
if (t == r) {
var a = QS[key][e];
return (typeof a != un && a && a.toString() ? e : "");
}
else {
Err(e3 + "(" + (e ? e : "") + ")");
}
}
QS[key].Key.toString = function() {
return x;
}
}
return key;
}
function AVTK(key, val) {
if (key != "") {
var key = AK(key);
var l = OL(QS[key]);
QS[key][l + 1] = val;
}
}
function TS(o) {
var s = "";
for (var i in o) {
var ty = typeof o[i];
if (ty == "object") {
s += TS(o[i]);
}
else if (ty != f) {
s += o[i] + ", ";
}
}
var l = s.length;
if (l > 1) {
return (s.substring(0, l-2));
}
return (s == "" ? x : s);
}
function KM(k, o) {
var k = k.toLowerCase();
for (var u in o) {
if (typeof o[u] != f && u.toString().toLowerCase() == k) {
return u;
}
}
}
if (window.location && window.location.search) {
LS = window.location.search;
var l = LS.length;
if (l > 0) {
LS = LS.substring(1,l);
var preAmpAt = 0;
var ampAt = -1;
var eqAt = -1;
var k = 0;
var skip = false;
for (var i = 0; i < l; ++i) {
var c = LS.charAt(i);
if (LS.charAt(preAmpAt) == "=" || (preAmpAt == 0 && i == 0 && c == "=")) {
skip=true;
}
if (c == "=" && eqAt == -1 && !skip) {
eqAt=i;
}
if (c == "&" && ampAt == -1) {
if (eqAt!=-1) {
ampAt=i;
}
if (skip) {
preAmpAt = i + 1;
}
skip = false;
}
if (ampAt>eqAt) {
AVTK(URID(LS.substring(preAmpAt, eqAt)), URID(LS.substring(eqAt + 1, ampAt)));
preAmpAt = ampAt + 1;
eqAt = ampAt = -1;
++k;
}
}
if (LS.charAt(preAmpAt) != "=" && (preAmpAt != 0 || i != 0 || c != "=")) {
if (preAmpAt != l) {
if (eqAt != -1) {
AVTK(URID(LS.substring(preAmpAt,eqAt)), URID(LS.substring(eqAt + 1,l)));
}
else if (preAmpAt != l - 1) {
AVTK(URID(LS.substring(preAmpAt, l)), "");
}
}
if (l == 1) {
AVTK(LS.substring(0,1),"");
}
}
}
}
var TC = OL(QS);
if (!TC) {
TC=0;
}
QS.toString = function() {
return LS.toString();
}
QS.Count = function() {
return (TC ? TC : 0);
}
QS.Count.toString = function() {
return (TC ? TC.toString() : "0");
}
QS.Item = function(e) {
if (typeof e == un) {
return LS;
}
else {
if (typeof e == n) {
var e = Math.ceil(e);
var c = 0;
for (var i in QS) {
if (typeof QS[i] != f && ++c == e) {
return QS[i];
}
}
Err(e1 + "().Item(" + e + ")");
}
else {
return QS[KM(e, QS)];
}
}
return x;
}
QS.Item.toString = function() {
return LS.toString();
}
QS.Key = function(e) {
var t = typeof e;
if (t == n) {
var e = Math.ceil(e);
var c = 0;
for (var i in QS) {
if (typeof QS[i] != f && ++c == e) {
return i;
}
}
}
else if (t == r) {
var e = KM(e, QS);
var a = QS[e];
return (typeof a != un && a && a.toString() ? e : "");
}
else {
Err(e2 + "().Key(" + (e ? e : "") + ")");
}
Err(e1 + "().Item(" + e + ")");
}
QS.Key.toString = function() {
Err(e2 + "().Key");
}
this.QueryString = function(k) {
if (typeof k == un) {
return QS;
}
else {
if (typeof k == n) {
return QS.Item(k);
}
var k = KM(k, QS);
if (typeof QS[k] == un) {
t = new Object();
t.Count = function() {
return 0;
}
t.Count.toString = function() {
return "0";
}
t.toString = function() {
return x;
}
t.Item = function(e) {
return x;
}
t.Item.toString = function() {
return x;
}
t.Key = function(e) {
Err(e3 + "(" + (e ? e : "") + ")");
}
t.Key.toString = function() {
return x;
}
return t;
}
else {
return QS[k];
}
}
}
this.QueryString.toString = function() {
return LS.toString();
}
this.QueryString.Count = function() {
return (TC ? TC : 0);
}
this.QueryString.Count.toString = function() {
return (TC ? TC.toString() : "0");
}
this.QueryString.Item = function(e) {
if (typeof e == un) {
return LS.toString();
}
else {
if (typeof e == n) {
var e = Math.ceil(e);
var c = 0;
for (var i in QS) {
if (typeof QS[i] != f && ++c == e) {
return QS[i];
}
}
Err(e1 + ".Item(" + e + ")");
}
else {
return QS[KM(e, QS)];
}
}
if (typeof e == n) {
Err(e1 + ".Item(" + e + ")");
}
return x;
}
this.QueryString.Item.toString = function() {
return LS.toString();
}
this.QueryString.Key = function(e) {
var t = typeof e;
if (t == n) {
var e = Math.ceil(e);
var c = 0;
for (var i in QS) {
if (typeof QS[i] == "object" && (++c == e)) {
return i;
}
}
}
else if (t == r) {
var e = KM(e, QS);
var a = QS[e];
return (typeof a != un && a && a.toString() ? e : "");
}
else {
Err(e2 + ".Key(" + (e ? e : "") + ")");
}
Err(e1 + ".Item(" + e + ")");
}
this.QueryString.Key.toString = function() {
Err(e2 + ".Key");
}
this.Version = 1.4;
this.Author = "Andrew Urquhart (http://andrewu.co.uk)";
}
var Request = new RObj(false);
How can i only display the string for the button that was clicked and not see both strings?
For identifying the button that's clicked, you need to have two forms. name1 and view_1 should be enclosed in one form and the other form should have name2 and view_2. This is the only way to identify the clicked button. If name1 is present then view_1 is clicked, if name2 is present then view_2 is clicked.
UPDATE: Added code sample
<form name="exampleform" id="exampleform" action="example123.html" method="get">
<fieldset>
<legend>Creating The Querystring</legend>
<label for="name_1">Name:</label>
<input type="text" name="name1" id="name_1" tabindex="1" size="40" value="Test1" />
<br />
<br />
<input type="submit" id='view_1' value="Submit" tabindex="2" />
</fieldset>
</form>
<br />
<br />
<form name="exampleform1" id="exampleform1" action="example123.html" method="get">
<fieldset>
<legend>Creating The Querystring</legend>
<label for="name_2">Name:</label>
<input type="text" name="name2" id="name_2" tabindex="1" size="40" value="Test2" />
<br />
<br />
<input type="submit" id='view_2' value="Submit" tabindex="2" />
</fieldset>
</form>
You are placing both name fields in one form. If you want just the one value, use two forms.
I rewrote your example page
Now you have 2 forms exampleform and exampleform2. Both submit data to the same page example123.html
Note also in the second form I renamed everything from name_2 to name_1 keeping it consistant with the first form
<form name="exampleform" id="exampleform" action="example123.html" method="get">
<fieldset>
<legend>Creating The Querystring</legend>
<label for="name_1">Name:</label>
<input name="name1" id="name_1" tabindex="1" size="40" value="Test1" type="text">
<br>
<br>
<input value="Submit" tabindex="2" type="submit">
<input value="Reset" tabindex="2" type="reset">
</fieldset>
</form>
<form name="exampleform2" id="exampleform2" action="example123.html" method="get">
<br>
<br>
<fieldset>
<legend>Creating The Querystring</legend>
<label for="name_1">Name:</label>
<input name="name1" id="name_1" tabindex="1" size="40" value="Test2" type="text">
<br>
<br>
<input value="Submit" tabindex="2" type="submit">
<input value="Reset" tabindex="2" type="reset">
</fieldset>
</form>
Now in your response page all you need to look for is
document.write("Name: " + Request.QueryString("name1"));
name2 no longer exists
[UPDATE]
As per a comment you made below. You can not have more then one submit button per form where they submit different data unless you validate the data onsubmit.
There is a serious security problem with what you are trying to do, as I will explain below. But you can still utilize your technique if you follow through.
Using your current code, you could do it by making sure the second file is named "example123.html", is saved in the same directory as the other file, and that your document.write() calls occur after the Request object is defined. Also check for null values, which are made particularly difficult by this class which returns an object rather than a string, so it can not be as easily compared with null.
var name1 = Request.QueryString("name1"),
name2 = Request.QueryString("name2");
if (name1+'' != 'null') {
document.write("Name: " + name1);
}
if (name2+'' != 'null') {
document.write("Name: " + name2);
}
That being said the code you are using follows a number of (other) bad practices, and while convenient perhaps for some people in mimicking the ASP Request behavior is really better abandoned in favor of other more standard practices.
We made a similar function for those coming instead from a PHP background (see http://phpjs.org/functions/import_request_variables:431 ) which if you use the following code, will let you access your variables like this:
ini_set('phpjs.getVarsObj', $_GET = {});
import_request_variables('g');
if ($_GET['name1']) {
document.write(htmlspecialchars($_GET['name1']));
}
if ($_GET['name2']) {
document.write(htmlspecialchars($_GET['name2']));
}
HOWEVER!!.... Please note the important warning though that if you use functions like the one you found (or ours), you are checking the URL for this information, since 1) your form is method=get, and 2) since client-side JavaScript can't by itself detect any other methods of how the data was sent to it, and thus if you are not careful about what you do with the $_GET variable's contents, someone could link someone to your site in such a way as to allow your site's visitor's cookie-stored passwords to be stolen or do other mischief. In other words, as with server-side code, be aware of XSS (Cross-site scripting).
For example, if someone filled in the name on your form with this code:
<script>alert('boo!');</script>
...in some browsers, besides for the person submitting the form, anyone who clicks on the link that results (e.g., if a hacker tempted someone to click it), will see that alert. This may not seem so serious, but if the JavaScript instead detects their cookie password on your site, they could craft it so that the script sends their cookies to their own site.
A somewhat safer solution is to use a function such as http://phpjs.org/functions/htmlspecialchars:426 to escape the potentially unsafe characters like < and & .
document.write(htmlspecialchars($_GET['name1']);
This function was based on the function of the same name in PHP, so it can be used there for the same purppose.
(If you actually WANT to allow HTML to be included in the page, that is more challenging and happens to be a question I just asked: JavaScript-based X/HTML & CSS sanitization )