Everything works fine when there is nothing in the email input, but as soon as I enter a "valid" email address, it doesn't even fire the function because the alert is never triggered. Any help will be appreciated.
Javascript (js/registration.js):
function validateForm() {
var value1 = document.forms["regForm"]["username"].value;
var value2 = document.forms["regForm"]["pass1"].value;
var value3 = document.forms["regForm"]["pass2"].value;
var value4 = document.forms["regForm"]["email"].value;
var atpos = value4.indexOf("#");
var dotpos = value4.lastIndexOf(".");
var check = true;
if(value1 == null || value1 == "") {
$("#userCheck").html("<img src='images/ico_fail.png'/> Please enter a user name! (25 character limit)");
check = false;
} else $("#userCheck").html("<img src='images/ico_pass.png'/>");
if(value2 == null || value2 == "") {
$("#pass1Check").html("<img src='images/ico_fail.png'/> Please enter a password! (25 character limit)");
check = false;
} else {
if(value2.length < 8) {
$("#pass1Check").html("<img src='images/ico_fail.png'/> Password must be 8 to 25 characters");
check = false;
} else $("#pass1Check").html("<img src='images/ico_pass.png'/>");
}
if(value3 == null || value3 == "") {
$("#pass2Check").html("<img src='images/ico_fail.png'/> Please re-enter your password! (25 character limit)");
check = false;
} else {
if(value3 != value2) {
$("#pass2Check").html("<img src='images/ico_fail.png'/> Password does not match!");
check = false;
} else $("#pass2Check").html("<img src='images/ico_pass.png'/>");
}
if(value4 == null || value4 == "") {
$("#emailCheck").html("<img src='images/ico_fail.png'/> Please enter a valid email!");
check = false;
} else {
if (atpos < 1 || dotpos < atpos + 2 || dotpos + 2 >= x.length) {
$("#emailCheck").html("<img src='images/ico_fail.png'/> Please enter a valid email!");
check = false;
} else $("#emailCheck").html("<img src='images/ico_pass.png'/>");
}
alert(check);
return check;
}
HTML:
<form name="regForm" method="post" action="" onsubmit="return validateForm();">
<input type="text" id="uName" name="username" size="25" maxlength="25" value=""/>
<span id="userCheck"> (25 character limit)</span></br>
<input type="password" id="password1" name="pass1" size="25" maxlength="25" value=""/>
<span id="pass1Check"> (25 character limit)</span></br>
<input type="password" id="password2" name="pass2" size="25" maxlength="25" value=""/>
<span id="pass2Check"></span></br>
<input type="text" name="email" size="25" value="" />
<span id="emailCheck"></span></br>
<input type="submit" name="submit" value="Register" />
<input type="hidden" name="perm" value="3" /> <!-- regular user -->
<input type="hidden" name="redirect" value="index.php" />
</form>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script type="text/javascript" src="js/registration.js"></script>
if (atpos < 1 || dotpos < atpos + 2 || dotpos + 2 >= x.length) {
You dont have x defined here. i think it should be value4.length
The problem is: ReferenceError: x is not defined
At this line:
if (atpos < 1 || dotpos < atpos + 2 || dotpos + 2 >= x.length) {
Related
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>
I have a list of valid user. I want that only these user will be able to send post request all other user should be identified as invalid user. I have written javascript code but unable to make invalid user to stop the execution of programs.
function validateForm() {
var x = document.forms["myForm"]["email"].value;
var atpos = x.indexOf("#");
var dotpos = x.lastIndexOf(".");
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length) {
alert("Not a valid e-mail address");
return false;
}
var eMailList = ["hankev#gmail.com", "slurp#gmail.com", "cofo#gmail.com", "vecrify#gmail.com"];
var i;
for (i=0; i< eMailList.length; i++){
if(x != eMailList[i]){
alert("Not a valid user");
return false;
}
}
}
<form name="myForm" action="/action_page_post.php" onsubmit="return validateForm();" method="post">
Email: <input type="text" name="email">
<input type="submit" value="Submit">
</form>
At first if you care about security issues, you shouldnt do it on the javascript side.
See code sample below:
function validateForm() {
var x = document.forms["myForm"]["email"].value;
var atpos = x.indexOf("#");
var dotpos = x.lastIndexOf(".");
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length) {
alert("Not a valid e-mail address");
return false;
}
var eMailList = ["hankev#gmail.com", "slurp#gmail.com", "cofo#gmail.com", "vecrify#gmail.com"];
var i;
if($.inArray(x,eMailList) == -1)
{
alert("Not a valid user");
}
else
{
alert("valid user");
}
}
<form name="myForm" action="/action_page_post.php" onsubmit="return validateForm();" method="post">
Email: <input type="text" name="email">
<input type="submit" value="Submit">
</form>
Link to JsFiddle
There is no need to loop through the array you can just use if(eMailList.indexOf(x) < 0) implemented below. The reason your code would always returns false is because that even if you enter a valid email it is not equal to every other item in the array.
function validateForm() {
var x = document.forms["myForm"]["email"].value;
var atpos = x.indexOf("#");
var dotpos = x.lastIndexOf(".");
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length) {
alert("Not a valid e-mail address");
return false;
}
var eMailList = ["hankev#gmail.com", "slurp#gmail.com", "cofo#gmail.com", "vecrify#gmail.com"];
if(eMailList.indexOf(x) < 0){
alert("Not a valid user");
return false;
}
}
<form name="myForm" action="/action_page_post.php" onsubmit="return validateForm();" method="post">
Email: <input type="text" name="email">
<input type="submit" value="Submit">
</form>
I am trying to give validation to both fields email and name but only email is getting validated and its not checking for name field. I am not able to find what is wrong in the code.
<html>
<body>
<form name="myForm">
Email: <input type="text" name="email" id="email2">
<br>
Name: <input type="text" name=" fname">
<button type="submit" name="submit" onclick="validateForm()">submit</button>
<br> email
<div id="email1"></div>
</form>
</body>
<script>
function validateForm() {
var x = document.forms["myForm"]["email"].value;
var atpos = x.indexOf("#");
var dotpos = x.lastIndexOf(".");
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length) {
alert("Not a valid e-mail address");
return false;
}
var email1 = document.getElementById("email2").value;
document.getElementById("email1").innerHTML=email1;
var y = document.forms["myForm"]["fname"].value;
if (y==null ||y=="") {
alert("name must be filled");
return false;
}
}
</script>
</html>
<input type="text" name=" fname">
There is a space before fname.That is why it is not working.You can try simple solution like this
You have missed giving id to Name: <input type="text" name=" fname"> Assign ID to Name: <input type="text" name=" fname" id="fname">.
As document.forms["myForm"]["fname"].value; this requires element id to fetch value.
Add an additional boolean to check your validation
function validateForm() {
var x = document.forms["myForm"]["email"].value;
//Additional boolean
var success = true;
var atpos = x.indexOf("#");
var dotpos = x.lastIndexOf(".");
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length) {
alert("Not a valid e-mail address");
success = false;
}
var email1= document.getElementById("email2").value;
document.getElementById("email1").innerHTML=email1;
var y = document.forms["myForm"]["fname"].value;
if (y==null ||y=="") {
alert("name must be filled");
success = false;
}
return success;
}
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
I have a form which I want it to be verified and validated by a try-catch block plus two other functions.
Here is what I have:
HTML:
<h5>Please enter your name below</h5>
<form name="textForm">
<label for="name">First name:</label>
<input type="text" name="fname" id="name">
</form>
<h5>Please enter your e-mail below</h5>
<form name="mailForm">
<label for="email">Email:</label>
<input type="email" name="email" id="email">
</form>
<form action="">
<label for="height">Your height:</label>
<input type="text" placeholder="in centimetres" name="personHeight" id="height" />
<br></br>
<input formaction="mailto:test#gmail.com" onclick="heightCheck();validateTextForm();validateMailForm();" type="submit" value="Submit all" id="submit" method="post" formtarget="_blank" />
<br></br>
<p id="mess"></p>
</form>
JS:
function validateTextForm() {
var x = document.forms["textForm"]["fname"].value;
if (x == null || x == "") {
alert("First name must be filled out");
return false;
}
}
function validateMailForm() {
var z = document.forms["mailForm"]["email"].value;
var atpos = z.indexOf("#");
var dotpos = z.lastIndexOf(".");
if (atpos < 1 || dotpos < atpos + 2 || dotpos + 2 >= z.length) {
alert("Not a valid e-mail address");
return false;
}
}
function heightCheck() {
try {
var x = document.getElementById("height").value;
if (x == "")
throw "enter your height";
if (isNaN(x)) throw "not a number";
if (x > 250)
throw "height is too high";
if (x < 80)
throw "height is too low";
} catch (err) {
var y = document.getElementById("mess");
y.innerHTML = "Error: " + err + ".";
}
}
The thing that i want it to happen is the following: Firstly, it does the form validation but afterwards if its correct, submits as well.
I tried to make it first verify the forms before actually submits but without any success.
While browsing i find out it could be done by either stopPropaganation, preventDefault or return false methods but still have no idea how to make it happen.
I will rep the guys who help me. Thanks in advance!
Fiddle: However in fiddle it doesn't run properly as it should: http://jsfiddle.net/5T9sJ/
You need to change your code according to my editions:
...
<input formaction="mailto:test#gmail.com" type="submit" value="Submit all" id="submit" method="post" formtarget="_blank" />
...
Then make processValidate method to wrap all other validations into it:
$(document).ready(function () {
$('input#submit').click(function (e) {
e.preventDefault();
validateTextForm();
validateMailForm();
heightCheck();
});
function validateTextForm() {
var x = document.forms["textForm"]["fname"].value;
if (x === null || x === "") {
alert("First name must be filled out");
return false;
}
}
function validateMailForm() {
var z = document.forms["mailForm"]["email"].value;
var atpos = z.indexOf("#");
var dotpos = z.lastIndexOf(".");
if (atpos < 1 || dotpos < atpos + 2 || dotpos + 2 >= z.length) {
alert("Not a valid e-mail address");
return false;
}
}
function heightCheck() {
try {
var x = document.getElementById("height").value;
if (x === "") throw "enter your height";
if (isNaN(x)) throw "not a number";
if (x > 250) throw "height is too high";
if (x < 80) throw "height is too low";
} catch (err) {
var y = document.getElementById("mess");
y.innerHTML = "Error: " + err + ".";
}
}
});
Explanation:
You have several methods bound on submit input type, so clicking on it will always call form submission.
I added jQuery click handler for this action to prevent the default action of submit button.
I think e.preventDefault() suits here the best.
WORKING DEMO: http://jsfiddle.net/rbegf/