Need a If and else statement and a new page - javascript

This is what i need help with!
My project needs a If and else statement for the Age part!
and then send the person who has validated correctly to a new page.. I currently have a page but that is just something that is in my USB
also need to explain how its is validating
Please help
!DOCTYPE html>
<html>
<head>
<script>
function validateForm() {
var x = document.forms["myForm"]["fname"].value;
if (x == null || x == "")
{
alert("Name must be filled out");
return false;
}
var Age = document.forms["myForm"]["Age"].value;
if (Age == null || Age == "") {
alert("Has to be a number between 1 and 150");
return false;
}
var Email = document.forms["myForm"]["Email"].value;
if (Email == null || Email == "") {
alert("Make sure it is the correct Email format");
return false;
}
var myCheck = document.getElementById("check1").checked;
if (myCheck == false) {
alert("Have to tick box to proceed");
return false;
}
}
</script>
</head>
<body>
<form name="myForm" action="file:///G:/Welcome.html"
onsubmit="return validateForm()" method="post">
Name: <input type="text" name="fname">
Age: <input type="text" name="Age">
Email: <input type="text" name="Email">
<br>checkbox: <input type="checkbox" id="check1" name="myCheck"> </br>
<input type="submit" value="click">
</form>
</body>
</html>

You could extend the if clause with the age check.
var age = document.forms["myForm"]["Age"].value;
if (age == "" || age < 1 || age > 150) {
// ^^^^^^^^^^^^^^^^^^^^^^^
alert("Has to be a number between 1 and 150");
return false;
}

I'd parse the value of the form into a number and then I'd check its range:
var age = Number(document.forms["myForm"]["Age"].value) || 0;
if (age < 1 || age > 150) {
alert("Has to be a number between 1 and 150");
return false;
}
Why convert to number and put Number(document.forms["myForm"]["Age"].value) || 0?
The reason is simple: imagine that a malicious user put in your form the value "NaN". If you didn't do this check, the value of age would be NaN and it'd pass your check (NaN < 1 is false and NaN > 150 is false too).
This way, if a user put "NaN" in the form, the guard would transform it into 0, the alert would trigger and the function would return false.

Related

Trouble with JavaScript Validation on Form

I am Trying to validate some input for a login form using JavaScript. From what I can see, everything in the script is correct, but it is not working. I'm sure it's a tiny thing that I've missed, any help would be appreciated.
Note: I am unable to use external libraries.
JavaScript code:
<script>
function validateForm() {
var x = document.forms["login"]["username"].value;
var y = document.forms["login"]["password"].value;
if (isNaN(x)) && (y === "") {
alert("Username must be numerical, and password must be entered!");
return false;
} else if (isNaN(x)) && (y !== "") {
alert("Username must be numerical!");
return false;
} else if (Number.isInteger(x) == true) && (y === "") {
alert("Password must be entered!");
return false;
} else {
return true;
}
}
</script>
HTML Code:
<form name="login" method="get">
<input type="text" placeholder="Customer ID" name="username">
<input type="password" placeholder="Password" name="password">
<input type="submit" onclick="return validateForm()" value="Log In" name="button">
<?php if (isset($errormessage)) { echo $errormessage; } ?>
</form>
(I'm very new to web dev, please don't judge too much :p)
In addition to other answers :
this line : var x = document.forms["login"]["username"].value; will store the value of username as a string, even if a numerical value is entered. Now I invite you to test the following line of code :
Number.isInteger('12')
It will return false.
One of the possible solutions would be to use parseInt on x before using it :
var x = parseInt(document.forms["login"]["username"].value);
It will still return NaN if a non int parsable value is given, and transform it to an int if the value is parsable.
Side Note :
parseInt('a') == NaN
parseInt('12') == 12
parseInt('12a') == 12
You were missing brackets around the conditions for if statements.
function validateForm() {
var x = document.forms["login"]["username"].value;
var y = document.forms["login"]["password"].value;
if ((isNaN(x)) && (y === "")) {
alert("Username must be numerical, and password must be entered!");
return false;
} else if ((isNaN(x)) && (y !== "")) {
alert("Username must be numerical!");
return false;
} else if ((Number.isInteger(x) == true) && (y === "")) {
alert("Password must be entered!");
return false;
} else {
return true;
}
}
<form name="login" method="get">
<input type="text" placeholder="Customer ID" name="username">
<input type="password" placeholder="Password" name="password">
<input type="submit" onclick="return validateForm()" value="Log In" name="button">
<?php if (isset($errormessage)) { echo $errormessage; } ?>
</form>
Let me know if you have any questions.
<script>
function validateForm() {
var x = document.forms["login"]["username"].value;
var y = document.forms["login"]["password"].value;
if ( (isNaN(x)) && (y === "")) {
alert("Username must be numerical, and password must be entered!");
return false;
} else if ( (isNaN(x)) && (y !== "")) {
alert("Username must be numerical!");
return false;
} else if ( (Number.isInteger(x) == true) && (y === "")) {
alert("Password must be entered!");
return false;
} else {
return true;
}
}
You have missed some parentheisis in your script please use this code
You've got extra parentheses in your if statement:
if (isNaN(x))<- this is closing the conditional and is not required
Remove that and it should work:
if (isNaN(x) && y === "") {
The else branches also have this issue, the whole if should appear like this:
if (isNaN(x) && y === "") {
alert("Username must be numerical, and password must be entered!");
return false;
} else if (isNaN(x) && y !== "") {
alert("Username must be numerical!");
return false;
} else if (Number.isInteger(x) == true && y === "") {
alert("Password must be entered!");
return false;
} else {
return true;
}
Also, the isNan function can be used from Number (just like isInteger) instead of global, this would make script more consistent :)

Javascript form validation. No error message. No popup

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

First check for errors before submitting

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/

How do I check to make sure form fields are not empty strings?

I am trying to get my validateForm() method to make sure email is valid (which I have done) and also make sure the 'name' and 'comments' fields are not empty. For some reason I cannot get the second part down, and need some assistance. Here is the current code I have.
<script type="text/javascript">
<!--
function validateForm() {
var x = document.forms["myForm"]["email"].value;
var x = document.forms["myForm"]["name"].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;
}
}
}
if (x == null || x == "") {
alert("Empty Fields");
return false;
}
}
// -->
</script>
And the form:
<form name="myForm" action="http://webdevfoundations.net/scripts/formdemo.asp" onsubmit="return validateForm()" method="POST">
Your name: <br>
<input type="text" name="name" ><br>
<br>
Your email: <br>
<input type="text" name="email"><br>
<br>
Your comments: <br>
<textarea name="comments" rows="15" cols="50"></textarea><br><br>
<input type="submit" value="Submit">
</form>
Why are you using same variable for both field name and email. It doesn't make sense.
There is one more syntax error in your code i.e. You have put an extra } before checking second condition. So it makes that condition outside of that function
function validateForm() {
var x = document.forms["myForm"]["email"].value;
var y = document.forms["myForm"]["name"].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;
}
if (x == "" || y == "") {
alert("Empty Fields");
return false;
}
}
So here is JS Fiddle Example
You are assigning both the form fields to the variable x
You should opt below points to keep in mind for above code
(1) validation for Empty fields should come first then Email checking.
(2) As per the code, your Empty field logic is not a part of validateForm() (It might be typo),so when validationForm() method will called,this logic won't execute
(3) you should write return true at the end of method validateForm()
(4) Use different variable names of field checking
GO through above points,it will be helpful to solve your Issue. :)
First there are syntax error in your code. It seems that there are two redunant curly braces. And then you assign both the two fields to x, and only the name field get its value. Also, you'd better first check the email field empty or not and then operate on it. Finally I don't think your check for email is right. For example: xxx#a.info. So you may try:
function checkEmail(aEmail){
var pattern=//w+([-+.']/w+)*#/w+([-.]/w+)*/./w+([-.]/w+)*/;
var objExp=new RegExp(pattern);
if(objExp.test(str)==true){
return true;
}else{
return false;
}
}
function validateForm() {
var x = document.forms["myForm"]["email"].value;
var y = document.forms["myForm"]["name"].value;
if (x == "" || y == "") {
alert("Empty Fields");
return false;
}
if (!checkEmail(y)) {
alert("Not a valid email");
return false;
}
}
You should try this way:
function validateForm(){
var x=document.forms["myForm"].getElementsByName('email').value;
var y=document.forms["myForm"].getElementsByName('name').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;
}
if (y==null || y==""){
alert("Empty Fields");
return false;
}
}

Javascript - Value not passing to function

So I have this form:
<form name="login" id="login" action="" method="POST" onSubmit="return test()">
<input type="text" size="10" name="username" /><div id="wrongUser"></div>
<br />
<input type="password" size="10" name="password" /><div id="wrongPass"></div>
<br />
<input type="submit" value="submit" name="submit" /><br /><br />
</form>
and these two functions:
function test()
{
var user = document.login.username.value;
var pass = document.login.password.value;
if((user == "" || user == null) && (pass == "" || pass == null))
{
document.getElementById('wrongUser').innerText = "Please Enter Username";
document.getElementById('wrongPass').innerText = "Please Enter Password";
return false;
}
if(checkEmpty(user, 'wrongUser', "Please Enter Username"))
return false
if(checkEmpty(pass, 'wrongPass', "Please Enter Password"))
return false;
return true;
}
function checkEmpty(name, id, output)
{
if(name == "" || name == null)
{
document.getElementById(id).innerText = "";
document.getElementById(id).innerText = output;
return true;
}
else
return false;
}
Now the functions kinda work but not how I would think. If the user only doesn't enter anything (first time) then they get the 2 errors. If the user enter just a username (second time) then the username error should disappear, but it doesn't. If I take it out of the function and replace the variables with their normal values then it works just fine. Why would it change when put in this function?
Put the document.getElementById().innerText = '' in the else, not in the if. Because you only reset the innerText when it's empty, but you would like to reset the tekst if it's not empty:
function checkEmpty( name, id, output ) {
var elem = document.getElementById(id); // it's faster to put the element in a var
if( name === undefined || name == '' name == null )
elem.innerText = output;
return true;
else
elem.innerText = '';
return false;
}

Categories