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>
Related
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>
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.
It seems that my original question was closed out. I was able to complete most of the form validation requirement for my Pizza form. However now I'm just stuck at the phone number validation and format.
I need assistants for form validation for my phone number.
The phone number must be Numbers only with Dash for example 222-222-2222 and anything else besides that format or an empty field should cause an alert when I hit my submit button and doe snot allow the form to be submitted unless it is correct
Please review my code for document.PizzaForm.phone.value code for my pizza form I'm not sure how to edit the code to achieve my requirement.
<html>
<head>
<title>Hello and JavaScript</title>
<script>
function doClear()
{
document.PizzaForm.customer.value = "";
document.PizzaForm.address.value = "";
document.PizzaForm.city.value = "";
document.PizzaForm.state.value = "";
document.PizzaForm.zip.value = "";
document.PizzaForm.phone.value = "";
document.PizzaForm.email.value = "";
document.PizzaForm.sizes[0].checked = false;
document.PizzaForm.sizes[1].checked = false;
document.PizzaForm.sizes[2].checked = false;
document.PizzaForm.sizes[3].checked = false;
document.PizzaForm.toppings[0].checked = false;
document.PizzaForm.toppings[1].checked = false;
document.PizzaForm.toppings[2].checked = false;
document.PizzaForm.toppings[3].checked = false;
document.PizzaForm.toppings[4].checked = false;
document.PizzaForm.toppings[5].checked = false;
document.PizzaForm.toppings[6].checked = false;
document.PizzaForm.toppings[7].checked = false;
document.PizzaForm.toppings[8].checked = false;
return;
}
function doSubmit()
{
if (validateText()==false)
{
alert("Required data missing in Step 1");
}
if (validateRadio()==false)
{
alert("Required data missing in Step 2");
}
if(validateTops()==false)
{
alert("Required data missing in Step 3");
}
var OrderWindow
OrderWindow = window.open("","","status,height=500,width=500");
OrderWindow.focus();
with (OrderWindow.document)
{
write("<h1><center>Customer Order Summary</center></h1><p>")
write("Name:" + document.PizzaForm.customer.value + "<br>")
write("Address:" + document.PizzaForm.address.value + "<br>")
write("City:" + document.PizzaForm.city.value + "<br>")
write("State:" + document.PizzaForm.state.value + "<br>")
write("Zip Code:" + document.PizzaForm.zip.value + "<br>")
write("Phone Number:" + document.PizzaForm.phone.value + "<br>")
write("E-Mail:" + document.PizzaForm.email.value + "<br>")
write("Pizza Size:" + validateRadio() + "<br>")
write("Pizza Toppings:" + validateTops() + "<br>")
write("<h3><center>Thank You for your Order.</center></h3><p>")
}
return;
}
function validateText()
{
if (document.PizzaForm.customer.value == "")
{
alert("Please provide your name");
document.PizzaForm.customer.focus();
}
if (document.PizzaForm.address.value == "")
{
alert("Please provide your address.");
document.PizzaForm.address.focus();
}
if (document.PizzaForm.city.value == "")
{
alert("Please provide your City.");
}
if (document.PizzaForm.state.value == "")
{
alert("Please provide your State.");
}
if (document.PizzaForm.zip.value == "" ||
isNaN( document.PizzaForm.zip.value ) ||
document.PizzaForm.zip.value.length != 5 )
{
alert("Please provide your Zip code.");
document.PizzaForm.zip.focus() ;
}
if (document.PizzaForm.phone.value == "" ||
isNaN( document.PizzaForm.phone.value ) ||
document.PizzaForm.phone.value.length != 10 )
{
alert("Please provide your phone number.");
document.PizzaForm.phone.focus() ;
}
var emailID = document.PizzaForm.email.value;
atpos = emailID.indexOf("#");
dotpos = emailID.lastIndexOf(".");
if (atpos < 1 || ( dotpos - atpos < 2 ))
{
alert("Please enter correct Email.")
document.myForm.Email.focus() ;
}
return (true);
}
function validateRadio()
{
if (document.PizzaForm.sizes[0].checked) true;
if (document.PizzaForm.sizes[1].checked) true;
if (document.PizzaForm.sizes[2].checked) true;
if (document.PizzaForm.sizes[3].checked) true;
return false;
}
function validateTops()
{
var sizes = document.PizzaForm.toppings;
var alert = ""
if (PizzaForm.toppings[0].checked) alert = "Pepperoni, " + alert;
if (PizzaForm.toppings[1].checked) alert = "Canadian Bacon, " + alert;
if (PizzaForm.toppings[2].checked) alert = "Sausage, " + alert;
if (PizzaForm.toppings[3].checked) alert = "Mushrooms, " + alert;
if (PizzaForm.toppings[4].checked) alert = "Pineapple, " + alert;
if (PizzaForm.toppings[5].checked) alert = "Black Olives, " + alert;
if (PizzaForm.toppings[6].checked) alert = "Extra Cheese, " + alert;
if (PizzaForm.toppings[7].checked) alert = "Plain, " + alert;
return alert;
}
</script>
</head>
<body>
<form Name ="PizzaForm">
<h1> The JavaScrpt Pizza Parlor</h>
<p>
<h4> Step 1: Enter your name, address, phone number, and email:</h4>
<font face="Courier New">
Name: <Input name="customer" size="50" type="text"><br>
Address: <Input name="address" size="50" type="text"><br>
City: <Input name="city" size="15"type="text">
State:<Input name="state" size="2"type="text"><br>
Zip: <Input name="zip" size="5"type="text"> <br>
Phone: <Input name="phone" size="50"type="text"><br>
Email: <Input name="email" size="31"type="text"><br>
</ font>
</ p>
<p>
<h4> Step 2: Select the size of pizza you want:</h4>
<font face="Courier New">
<input name="sizes" type="radio">Small
<input name="sizes" type="radio">Medium
<input name="sizes" type="radio">Large
<input name="sizes" type="radio">Jumbo<br>
</font>
</ p>
<p>
<h4> Step 3: Select the pizza toppings you want:</h4>
<font face="Courier New">
<input name="toppings" type="checkbox">Pepperoni
<input name="toppings" type="checkbox">Canadian Bacon
<input name="toppings" type="checkbox">Sausage<br>
<input name="toppings" type="checkbox">Mushrooms
<input name="toppings" type="checkbox">Pineapple
<input name="toppings" type="checkbox">Black Olives<br>
<input name="toppings" type="checkbox">Green Peppers
<input name="toppings" type="checkbox">Extra Cheese
<input name="toppings" type="checkbox">Plain
</ font>
</ p>
<input type="button" value="Submit Order" onClick="doSubmit()">
<input type="button" value="Clear Entries" onClick="doClear()">
</form>
</body>
</html>
The phone number must be Numbers only with Dash for example 222-222-2222
You can use a regex to check your phone number. This will match exactly 3 digits, a dash, 3 digits, a dash, and a final 4 digits.
var phone = "222-222-2222";
if (!/^\d{3}-\d{3}-\d{4}$/.test(phone)) {
console.log("bad number");
} else {
console.log("good number");
}
Then change your code to this:
if (!/^\d{3}-\d{3}-\d{4}$/.test(document.PizzaForm.phone.value)) {
alert("Please provide a correct phone number.");
document.PizzaForm.phone.focus();
}
If you are more flexible on your phone number format, for example allowing brackets around the area code, then please see below for more solutions:
http://www.regexplanet.com/advanced/javascript/index.html
https://www.safaribooksonline.com/library/view/regular-expressions-cookbook/9781449327453/ch04s02.html
What about an alert for a blank field that says please enter phone number?
// This will treat empty strings, spaces and tabs as "empty"
function isEmpty(str){
return !str.replace(/^\s+/g, '').length;
}
if (isEmpty(document.PizzaForm.phone.value)) {
alert("Please enter a phone number.");
document.PizzaForm.phone.focus();
} else if (!/^\d{3}-\d{3}-\d{4}$/.test(document.PizzaForm.phone.value)) {
alert("Please provide a correct phone number.");
document.PizzaForm.phone.focus();
}
Assuming that's the pattern you want (xxx-xxx-xxxx), including the dashes, this works:
function validatePhone(ipt){
if(ipt.search('[0-9]{3}-[0-9]{3}-[0-9]{4}') === 0 && ipt.length === 12){
return true;
} else {
return false;
}
}
console.log(validatePhone('123-456-7890'));
console.log(validatePhone('abc-def-ghij'));
console.log(validatePhone('123-456-789'));
Of course, leave out the testing code.
I actually recommend letting them use dashes, slashes, or whatever, then just parsing them out:
window.verify = function() {
var phone = document.getElementById("phone").value.split("");
var verified = "";
for (var char in phone)
{
verified += parseInt(phone[char]) >= 0 ? phone[char] : "";
}
var len = verified.length;
if (len != 7 && len != 10)
{
alert("Invalid number of digits!");
}
else
{ // then format the resulting number as you see fit
var finalNum = "";
if (len == 10)
{
finalNum += verified.substring(0,3) + "-"
verified = verified.substring(3);
}
finalNum += verified.substring(0,3) + "-";
verified = verified.substring(3);
finalNum += verified;
alert(""+finalNum);
}
}
<input type="text" id="phone" />
<br>
<br>
<button type="button" onclick="verify()">Validate Phone</button>
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) {
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;
}