Javascript - Value not passing to function - javascript

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;
}

Related

How can I prevent my form from being submitted?

I want the form to not be submitted when the inputs are wrong. The error messages do appear but my form still gets submitted nonetheless. I cant seem to find the problem would appreciate the help thank you :)-----------------------------------------------------------------------------------------------------
<form action="/handleServer.php" method="get" onsubmit="return validateForm()">
<!-- starting with first name-->
<h4 class="heading" >First name:</h4>
<input id="fname" type="text" name="fname" size="30">
<span id="errorName" class="error"></span>
<!-- module code -->
<h4 class="heading">Module code:</h4>
<input id="mcode" type="text" name="mcode" size="30">
<span id="errorCode" class="error"></span>
<input type="submit" value="Submit">
</form>
<script>
//input field using if-else statements
function validateForm() {
var fname = document.getElementById("fname").value;
var mcode = document.getElementById("mcode").value;
var errorN = document.getElementById("errorName");
var errorC = document.getElementById("errorCode");
//test for an empty input
if (fname === '' && mcode === '') {
errorN.innerHTML = "Please fill in the blank";
errorC.innerHTML = "Please fill in the blank";
return false;
}
if (fname === '') {
errorN.innerHTML = "Please fill in the blank";
return false;
} else {
errorN.innerHTML = "";
}
if (mcode === '') {
errorC.innerHTML = "Please fill in the blank";
return false;
} else {
errorC.innerHTML = "";
}
//test for invalid format
if (/^[A-Z]\D{2,30}$/.test(fname) == false) //if its true, it will go to the second input
{
errorN.innerHTML = "One capital letter and no digits allowed";
fname.style.color="red";
return false;
} else {
fname.innerHTML = "";
}
if (/^[a-z]{3}[1-9]\d{4}$/.test(mcode) == false)
{
errorC.innerHTML = "Wrong format";
mcode.style.color="red";
return false;
} else {
mcode.innerHTML = "";
}
return true; }
The problem seems to be these four lines of code:
fname.style.color="red";
fname.innerHTML = "";
mname.style.color="red";
mname.innerHTML = "";
fname and mname are strings, therfore fname.style and mname.style both result in undefined. Obviously you can't set properties on undefined which is why you are getting an error.
//You are getting the value properties which are strings:
var fname = document.getElementById("fname").value;
var mcode = document.getElementById("mcode").value;
The error is stopping your code before you can return false, preventing the cancelation of the form submit.
The solution is to instead make two more variables storing the actual input elements:
var finput = document.getElementById("fname");
var minput = document.getElementById("mname");
Then change lines:
fname.style.color="red";
fname.innerHTML = "";
mname.style.color="red";
mname.innerHTML = "";
to:
finput.style.color="red";
finput.innerHTML = "";
minput.style.color="red";
minput.innerHTML = "";
Here is a working version:
<form action="/handleServer.php" method="get" onsubmit="return validateForm()">
<!-- starting with first name-->
<h4 class="heading">First name:</h4>
<input id="fname" type="text" name="fname" size="30">
<span id="errorName" class="error"></span>
<!-- module code -->
<h4 class="heading">Module code:</h4>
<input id="mcode" type="text" name="mcode" size="30">
<span id="errorCode" class="error"></span>
<input type="submit" value="Submit">
</form>
<script>
//input field using if-else statements
function validateForm() {
var finput = document.getElementById("fname");
var minput = document.getElementById("mname");
var fname = document.getElementById("fname").value;
var mcode = document.getElementById("mcode").value;
var errorN = document.getElementById("errorName");
var errorC = document.getElementById("errorCode");
//test for an empty input
if (fname === '' && mcode === '') {
errorN.innerHTML = "Please fill in the blank";
errorC.innerHTML = "Please fill in the blank";
return false;
}
if (fname === '') {
errorN.innerHTML = "Please fill in the blank";
return false;
} else {
errorN.innerHTML = "";
}
if (mcode === '') {
errorC.innerHTML = "Please fill in the blank";
return false;
} else {
errorC.innerHTML = "";
}
//test for invalid format
if (/^[A-Z]\D{2,30}$/.test(fname) == false) //if its true, it will go to the second input
{
errorN.innerHTML = "One capital letter and no digits allowed";
finput.style.color = "red";
return false;
} else {
finput.innerHTML = "";
}
if (/^[a-z]{3}[1-9]\d{4}$/.test(mcode) == false) {
errorC.innerHTML = "Wrong format";
minput.style.color = "red";
return false;
} else {
minput.innerHTML = "";
}
return true;
}
</script>
Pass the event to the form validation function
onsubmit="return validateForm(e)"
Then prevent default submission using
e.preventDefault();
Your return statement should be inside a condition. Right now you're existing the condition and ending the function with a return true; regardless of what the conditional statements have already returned. So:
if (fname === '' && mcode === '') {
errorN.innerHTML = "Please fill in the blank";
errorC.innerHTML = "Please fill in the blank";
return false;
}else{
return true; // THIS IS WHERE YOU NEED TO RETURN TRUE
}
I see you're returning false in multiple if statements. You'll need to find a way to unify the conditions so that you have one return only for for either true or false.

A Simple Form with Validation in JavaScript [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
I would like to modify a JavaScript Code and add an extra field such as:
The first text box for the user to enter his/her address,
The second text box for the user to enter a telephone number.
The Code looks like so:
var myForm = document.form1;
function btnCheckFormClick(e) {
var txtName = myForm.txtName;
var txtAge = myForm.txtAge;
if (txtAge.value == "" || txtName.value == "") {
alert("Please complete all of the form");
if (txtName.value == "") {
txtName.focus();
} else {
txtAge.focus();
}
} else {
alert("Thanks for completing the form " + txtName.value);
}
}
function txtAgeBlur(e) {
var target = e.target;
if (isNaN(target.value)) {
alert("Please enter a valid age");
target.focus();
target.select();
}
}
function txtNameChange(e) {
alert("Hi " + e.target.value);
}
myForm.txtName.addEventListener("change", txtNameChange);
myForm.txtAge.addEventListener("blur", txtAgeBlur);
myForm.btnCheckForm.addEventListener("click", btnCheckFormClick);
<form action="" name="form1">
Please enter the following details:
<p>
Name:
<input type="text" name="txtName" />
</p>
<p>
Age:
<input type="text" name="txtAge" size="3" maxlength="3" />
</p>
<p>
<input type="button" value="Check details" name="btnCheckForm">
</p>
</form>
Here is what I tried already BUt it's not working(Not Validation):
var myForm = document.form1;
function btnCheckFormClick(e) {
var txtName = myForm.txtName;
var txtAge = myForm.txtAge;
var txtAddress = myForm.txtAddress;
var txtTelNumber = myForm.txtTelNumber;
if (txtAge.value == "" || txtName.value == "" && txtAddress.value == "" || txtTelNumber.value == "") {
alert("Please complete all of the form");
if (txtName.value == "" && txtAddress.value == "" && txtTelNumber.value == "") {
txtName.focus();
} else {
txtAge.focus();
} else {
txtAddress.focus();
} else {
txtTelNumber.focus();
} else {
alert("Thanks for completing the form " + txtName.value);
}
}
}
function txtAgeBlur(e) {
var target = e.target;
if (isNaN(target.value)) {
alert("Please enter a valid age");
target.focus();
target.select();
}
}
function txtTelNumberBlur(e) {
var target = e.target;
if (isNaN(target.value)) {
alert("Please enter a valid number");
target.focus();
target.select();
}
}
function txtAddressChange(e) {
alert("Your address is: " + e.target.value);
}
function txtNameChange(e) {
alert("Hi " + e.target.value);
}
myForm.txtName.addEventListener("change", txtNameChange);
myForm.txtAge.addEventListener(, txtAgeBlur);
myForm.txtAddress.addEventListener("change", txtAddressChange);
myForm.txtTelNumber.addEventListener("change", txtTelNumberBlur);
myForm.btnCheckForm.addEventListener("click", btnCheckFormClick);
<form action="" name="form1">
Please enter the following details:
<p>
Name:
<input type="text" name="txtName" />
</p>
<p>
Age:
<input type="text" name="txtAge" size="3" maxlength="3" />
</p>
Address:
<input type="text" name="txtAddress" size="40" maxlength="25" />
</p>
Telephone Number:
<input type="text" name="txtTelNumber" size="20" maxlength="10" />
</p>
<p>
<input type="button" value="Check details" name="btnCheckForm">
</p>
</form>
Can anyone tell me what am I doing wrong and point me out to where look at?
Thanks.
You can't have multiple else blocks for the same if. You should be checking each field in a separate else if block.
And in the outer if, all the checks must be connected with ||. You had a mix of && and ||.
var myForm = document.form1;
function btnCheckFormClick(e) {
var txtName = myForm.txtName;
var txtAge = myForm.txtAge;
var txtAddress = myForm.txtAddress;
var txtTelNumber = myForm.txtTelNumber;
if (txtAge.value == "" || txtName.value == "" || txtAddress.value == "" || txtTelNumber.value == "") {
alert("Please complete all of the form");
if (txtName.value == "") {
txtName.focus();
} else if (txtAge.value == "") {
txtAge.focus();
} else if (txtAddress.value == "") {
txtAddress.focus();
} else if (txtTelNumber.value == "") {
txtTelNumber.focus();
}
} else {
alert("Thanks for completing the form " + txtName.value);
}
}
function txtAgeBlur(e) {
var target = e.target;
if (isNaN(target.value)) {
alert("Please enter a valid age");
target.focus();
target.select();
}
}
function txtTelNumberBlur(e) {
var target = e.target;
if (isNaN(target.value)) {
alert("Please enter a valid number");
target.focus();
target.select();
}
}
function txtAddressChange(e) {
alert("Your address is: " + e.target.value);
}
function txtNameChange(e) {
alert("Hi " + e.target.value);
}
myForm.txtName.addEventListener("change", txtNameChange);
myForm.txtAge.addEventListener("blur", txtAgeBlur);
myForm.txtAddress.addEventListener("change", txtAddressChange);
myForm.txtTelNumber.addEventListener("change", txtTelNumberBlur);
myForm.btnCheckForm.addEventListener("click", btnCheckFormClick);
<form action="" name="form1">
Please enter the following details:
<p>
Name:
<input type="text" name="txtName" />
</p>
<p>
Age:
<input type="text" name="txtAge" size="3" maxlength="3" />
</p>
Address:
<input type="text" name="txtAddress" size="40" maxlength="25" />
</p>
Telephone Number:
<input type="text" name="txtTelNumber" size="20" maxlength="10" />
</p>
<p>
<input type="button" value="Check details" name="btnCheckForm">
</p>
</form>

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>

Javascript code won't work on my form [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
I am working on a form but my form is not working whenever I press submit. I am trying to evaluate whether sections of the form is empty, the email, and the number of digits for a user id. When I press submit nothing happens and I have been stuck like this for a while. FYI I have to use plain js and html.
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Student Login Form</title>
<link rel='stylesheet' href='studentform.css' type='text/css' />
<script src="studentform.js"></script>
</head>
<body onload="document.form.studentid.focus();">
<h1>Student Login</h1>
<div class="container">
<form name="form" onsubmit="return validate();">
<label for="studentid">Student ID:</label>
<input type="number" name="studentid" maxlength="8" id="studentid" required />
<label for="name">Name:</label>
<input type="text" name="name" size="50" id="name" required />
<label for="email">Email:</label>
<input type="email" name="email" size="50" id="email" required />
<label for="emailconfirm">Email Confirmation:</label>
<input type="checkbox" name="emailconfirm" checked /><span>Send an email confirmation</span>
<select>
<option selected>Student Registration</option>
<option>Transcript</option>
</select>
<input type="submit" name="submit" value="Submit" />
</form>
</div>
`
Js.
function validate(){
var studentid = document.getElementById("studentid").value;
var name = document.getElementById("name").value;
var email = document.getElementById("email").value;
if(nameEmpty(name))
{
if(studentidEmpty(studentid))
{
if(emailEmpty(email))
{
if(digitCheck(studentid))
{
if checkEmail(email)
{
verify(name, studentid)
}
}
}
}
}
return false;
}
function studentidEmpty(studentid){
if ( studentid == "" ){
alert("Please provide your student id!");
studentid.focus();
return false;
}
}
function nameEmpty(name){
if ( name == "" ){
alert("Please provide your name!");
name.focus() ;
return false;
}
}
function emailEmpty(email){
if( email == "" ){
alert( "Please provide your email!" );
email.focus();
return false;
}
function digitCheck(studentid){
var ok = studentid.search(".{8,}");
if (ok!=0){
alert("Please provide ID with 8 digits.");
return false;
}
}
function checkEmail(email) {
var filter = /^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
if (!filter.test(email.value)) {
alert('Please provide a valid email address');
email.focus;
return false;
}
}
function verify(name, studentid){
var personList = [["Joe",11111111],["Tammy",22222222],["Jones",33333333]];
for (list in personList) {
if (name in list && studentid in list){
alert("Welcome! An email verification with be sent soon.");
return true;
} else{
alert("Student Name and/or ID not found in records");
return false;
}
}
}
}
I think you should fix this line:
if checkEmail(email)
to
if (checkEmail(email))
you have forgotten the parentheses.
Edit:
I have completely fixed your code. Your errors:
you have forgotten to add else clauses for your field checkers, they were only returning false if the validation failed
your checking "if array contains value" was wrong, I have added a method from here
you were trying to focus on the values, not tags
you were trying to test email value from the "value of the value" not "value"
function validate() {
var studentid = document.getElementById("studentid").value;
var name = document.getElementById("name").value;
var email = document.getElementById("email").value;
if (nameEmpty(name)) {
if (studentidEmpty(studentid)) {
if (emailEmpty(email)) {
if (digitCheck(studentid)) {
if (checkEmail(email)) {
return verify(name, studentid);
}
}
}
}
}
return false;
}
function studentidEmpty(studentid) {
if (studentid == "") {
alert("Please provide your student id!");
document.getElementById("studentid").focus();
return false;
} else {
return true;
}
}
function nameEmpty(name) {
if (name == "") {
alert("Please provide your name!");
document.getElementById("name").focus();
return false;
} else {
return true;
}
}
function emailEmpty(email) {
if (email == "") {
alert("Please provide your email!");
document.getElementById("email").focus();
return false;
} else {
return true;
}
}
function digitCheck(studentid) {
var ok = studentid.search(".{8,}");
if (ok != 0) {
alert("Please provide ID with 8 digits.");
return false;
} else {
return true;
}
}
function checkEmail(email) {
var filter = /^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
if (!filter.test(email)) {
alert('Please provide a valid email address');
email.focus;
return false;
} else {
return true;
}
}
function verify(name, studentid) {
var personList = [
["Joe", 11111111],
["Tammy", 22222222],
["Jones", 33333333]
];
for (list in personList) {
if (contains.call(list, name) && contains.call(list, studentid)) {
alert("Welcome! An email verification with be sent soon.");
return true;
}
}
alert("Student Name and/or ID not found in records");
return false;
}
var contains = function(needle) {
// Per spec, the way to identify NaN is that it is not equal to itself
var findNaN = needle !== needle;
var indexOf;
if(!findNaN && typeof Array.prototype.indexOf === 'function') {
indexOf = Array.prototype.indexOf;
} else {
indexOf = function(needle) {
var i = -1, index = -1;
for(i = 0; i < this.length; i++) {
var item = this[i];
if((findNaN && item !== item) || item === needle) {
index = i;
break;
}
}
return index;
};
}
return indexOf.call(this, needle) > -1;
};
<div>
<form>
<label for="name">Name:</label>
<input type="text" name="name" size="50" id="name" required />
<label for="studentid">Student ID:</label>
<input type="number" name="studentid" maxlength="8" id="studentid" required />
<label for="email">Email:</label>
<input type="email" name="email" size="50" id="email" required />
<label for="emailconfirm">Email Confirmation:</label>
<input type="checkbox" name="emailconfirm" checked /><span>Send an email confirmation</span>
<select>
<option selected>Student Registration</option>
<option>Transcript</option>
</select>
<input onclick="return validate();" type="submit" name="submit" value="Submit" />
</form>
</div>
Validate function always return false !! It shouldn't.
function validate(){
var studentid = document.getElementById("studentid").value;
var name = document.getElementById("name").value;
var email = document.getElementById("email").value;
return nameEmpty(name) && studentidEmpty(studentid) && emailEmpty(email) && digitCheck(studentid) && checkEmail(email) && verify(name, studentid);
}
Then be sure your form looks like :
<form name="form" onsubmit="return validate();" action="javascript:void(0)">
</form>
And your autofocus input to look like :
<input type="number" name="studentid" maxlength="8" id="studentid" required autofocus/>
You're forgetting the parentheses.
It is also wrong to start and end each function, try using the code below with these corrections.
function validate() {
var studentid = document.getElementById("studentid").value;
var name = document.getElementById("name").value;
var email = document.getElementById("email").value;
if (nameEmpty(name)) {
if (studentidEmpty(studentid)) {
if (emailEmpty(email)) {
if (digitCheck(studentid)) {
if (checkEmail(email)) {
verify(name, studentid)
}
}
}
}
}
return false;
}
function studentidEmpty(studentid) {
if (studentid == "") {
alert("Please provide your student id!");
studentid.focus();
return false;
}
}
function nameEmpty(name) {
if (name == "") {
alert("Please provide your name!");
name.focus();
return false;
}
}
function emailEmpty(email) {
if (email == "") {
alert("Please provide your email!");
email.focus();
return false;
}
}
function digitCheck(studentid) {
var ok = studentid.search(".{8,}");
if (ok != 0) {
alert("Please provide ID with 8 digits.");
return false;
}
}
function checkEmail(email) {
var filter = /^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
if (!filter.test(email.value)) {
alert('Please provide a valid email address');
email.focus;
return false;
}
}
function verify(name, studentid) {
var personList = [
["Joe", 11111111],
["Tammy", 22222222],
["Jones", 33333333]
];
for (list in personList) {
if (name in list && studentid in list) {
alert("Welcome! An email verification with be sent soon.");
return true;
} else {
alert("Student Name and/or ID not found in records");
return false;
}
}
}

Need a If and else statement and a new page

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.

Categories