JavaScript Form Validation Not Working onSubmit - javascript

I'm working through a section of a book on form validation with JavaScript. Unfortunately, the example in the book isn't working. I understand and follow the logic behind the validation (The general idea is that if any of the individual field validation functions return a value to the validate function then an alert will display and the form will not be submitted onSubmit) , but nothing is happening onSubmit. I have looked over the script and html a few times and can't find anything wrong (I even went to the book site and copied the code from there).
Here is the html form and the JavaScript validation:
<script>
function validate(form)
{
fail = validateForename(form.forename.value)
fail += validateSurname(form.surname.value)
fail += validateUsername(form.username.value)
fail += validatePassword(form.password.value)
fail += validateAge(form.age.value)
fail += validateEmail(form.email.value)
if (fail == "") return true
else {alert(fail); return false }
}
</script>
<script>
function validateForename(field) {
if (field == "") return "No Forename was entered.\n"
return ""
}
function validateSurname(field) {
if (field == "") return "No Surname was entered.\n"
return ""
}
function validateUsername(field) {
if (field == "") return "No Username was entered.\n"
else if (field.length < 5) return "Usernames must be at least 5 characters.\n"
else if (/[^a-zA-Z0-9_-]/.test(field)) return "Only a-z, A-Z, 0-9, - and _ allowed in Usernames.\n"
return ""
}
function validatePassword(field) {
if (field == "") return "No Password was entered.\n"
else if (field.length < 6) return "Passwords must be at least 6 characters.\n"
else if (! /[a-z]/.test(field) || ! /[A-Z]/.test(field) || ! /[0-9]/.test(field)) return "Passwords require one each of a-z, A-Z and 0-9.\n"
return ""
}
function validateAge(field) {
if (isNAN(field)) return "No Age was entered.\n"
else if (field < 18 || field > 110) return "Age must be between 18 and 110.\n"
return ""
}
function validateEmail(field) {
if (field == "") return "No Email was entered.\n"
else if (!((field.indexOf(".") > 0) && (field.indexOf("#") > 0)) || /[^a-zA-Z0-9.#_-]/.test(field)) return "The Email address is invalid.\n"
return ""
}
</script>
</head>
<body>
<table class="signup" border="0" cellpadding="2" cellspacing="5" bgcolor="#eeeeee">
<th colspan="2" align="center">Signup Form</th>
<form method="post" action="adduser.php" onSubmit="return validate(this)">
<tr><td>Forename</td><td><input type="text" maxlength="32" name="forename" /></td>
</tr><tr><td>Surname</td><td><input type="text" maxlength="32" name="surname" /></td>
</tr><tr><td>Username</td><td><input type="text" maxlength="16" name="username" /></td>
</tr><tr><td>Password</td><td><input type="text" maxlength="12" name="password" /></td>
</tr><tr><td>Age</td><td><input type="text" maxlength="3" name="age" /></td>
</tr><tr><td>Email</td><td><input type="text" maxlength="64" name="email" /></td>
</tr><tr><td colspan="2" align="center">
<input type="submit" value="Signup" /></td>
</tr></form></table>
</body>
</html>

nothing is happening onSubmit
Assuming that you really do mean that nothing is happening, and that that includes "the form being submitted" then the problem is one that could be resolved by making the HTML valid.
A form cannot be wrapped around table rows and be inside the table those rows belong to. Some browsers recover from this error my moving the form to after the table (but leaving the inputs inside the table). This means that the inputs are not inside the form and sit around doing nothing.
As a quick fix, move the form so it surrounds the table.
As a proper solution, stop using tables for layout. CSS is a good tool for form layout.
You should also take advantage of the label element, and not fill your JS with globals.

Here's a hint.. how do you spell "isNAN"?
This code is easily debugged by putting alert statements after each line of code. If you use simple debugging like this, you will find that you have some invalid syntax. I leave it to you to find the bug!

Replace isNAN with isNaN and it should work.

Related

Form input check Javascript

I have an html form and want to create a Javascript code that would check if the Tel. field include only numbers. It is an exercise so I don't want to use jQuery or any other library. I put together this:
HTML
<form action="" method="post" enctype="multipart/form-data" name="form1" id="form1" onsubmit="return numberedFieldsCheck()">
<table>
<tr>
<td>
<label for="tel">Telephone</label></td>
<td>
<input type="text" placeholder="00441293603275" name="tel" id="tel" />
<span id="telFieldIntCheck" style="display:none;color:red">You can only use numbers.</span>
</td>
<td>
<input type="submit" name="button" id="button" value="Submit" />
</td>
</tr>
</table></form>
JS
function numberedFieldsCheck(){
var x=document.getElementById('tel').value;// retrieving value from the form
console.log(x);
if(!integerCheck(x)){
alert('wrong format');
document.getElementById('telFieldIntCheck').style.display="inline";
return false;
}
}
function integerCheck(userInput) {
var userInputArr=userInput.split('');
for (i=0;i<userInputArr.length;i++){
if (typeof userInputArr[i]=="number")
{console.log('format ok')}
else {return false};
}
}
Can you help me with the code? It alerts wrong format regardless of what I put into the input field. Console logs appear for a millisecond and disappear straight away.
Since you only need to check if the field contains only numbers, this should work :
function numberedFieldsCheck(){
var x=document.getElementById('tel').value;
// Checks if the field is empty.
if(x.trim() == '') {
alert("Tel field can't be empty.");
return false;
}
if(!integerCheck(x)){
alert('Wrong format !');
document.getElementById('telFieldIntCheck').style.display="inline";
return false;
}
alert("Alright !");
// Note that this return true is important. You weren't
// returning anything even in the case where everything was fine.
// If you don't, it will return 'undefined' by default, which is
// casted to 'false' in checks. So that means the function returns
// false even if everything is alright.
return true;
}
function integerCheck(userInput) {
// Now, all the elements of usrInputArr will contain strings only.
// That means typeof <element> will always return "string".
var userInputArr=userInput.split('');
for (i=0;i<userInputArr.length;i++){
char = userInputArr[i];
// Comparing by ASCIIs should work just fine.
if (! (char >= '0' && char <= '9' || char == ' ') )
return false;
}
return true;
}
You should also do what #hindmost said in the comments of your question i.e. changing the forms onsubmit to return numberFieldCheck().

How come my JavaScript isn't working?

I am doing a login page for school. I have written the page, but the JavaScript does not seem to work with the form. I have checked over both the form and the JavaScript multiple times, but I see no mistake. Can anyone help me?
function processInfo() {
var theusername;
var thepassword;
theusername = document.myForm.username.value;
thepassword = document.myForm.password.value;
if (document.myForm.username.value = "") {
alert("Please enter in the username.")
return false;
} else if (document.myForm.password = "") {
alert("Please enter in the password.")
return false;
} else if (document.myForm.username.value != "andrew123") {
document.myForm.txtOutput.value = "Incorrect username or password."
} else if (thepassword != "abc") {
document.myForm.txtOutput.value = "Incorrect username or password."
} else if (theusername == "andrew123"
thepassword == "abc") {
document.myForm.txtOutput.value = "Correct! You have successfully logged in."
}
}
<form name="myForm">
<b>User Name:</b>
<input type="text" name="username" size="36" maxlength="100">
<b>Password:</b>
<input type="text" name="password" size="36" maxlength="100">
<p>
<input type=button value="VERIFY INFORMATION" onClick=processInfo()>
</p>
<textarea name="txtOutput" rows=1 cols=4 0></textarea>
</form>
= is an assignment, you keep using it when you are trying to perform a comparison (which would use == or ===).
Sometimes you try to compare the form control with a string instead of getting its .value.
You forgot to put a boolean AND between the two conditions you have theusername == "andrew123"
thepassword == "abc"
You should learn to use the console in your browser as most of these problems would be highlighted in it or could be with the addition of a little logging.

How to make input required

What I want is that when both fields i.e. fname and lname are kept empty, the pop-up window should show both messages i.e. "First name must be filled out", "Last name must be filled out".
What modifications do I need to do?
<!DOCTYPE html>
<html>
<head>
<script>
function validateForm() {
var x = document.forms["myForm"]["fname"].value;
if (x == null || x == "") {
alert("First name must be filled out");
document.myForm.fname.focus();
return false;
}
var y = document.forms["myForm"]["lname"].value;
if (y == null || y == "") {
alert("Last name must be filled out");
document.myForm.lname.focus();
return false;
}
}
</script>
</head>
<body>
<form name="myForm" action="demo_form.asp" onsubmit="return validateForm()" method="post">First name:
<input type="text" name="fname">Last name:
<input type="text" name="lname">
<input type="submit" value="Submit">
</form>
</body>
Perhaps this will give you some ideas about how to proceed:
function validateForm() {
var errors = [],
fname = document.forms["myForm"]["fname"],
lname = document.forms["myForm"]["lname"];
if (lname.value == "") {
errors.unshift("Last name must be filled out");
lname.focus();
}
if (fname.value == "") {
errors.unshift("First name must be filled out");
fname.focus();
}
if (errors.length > 0) {
alert("Cannot submit\n" + errors.join("\n"));
return false;
}
}
Demo: http://jsfiddle.net/MKdg5/
The first thing you'll notice is that it is easier to read because blocks are indented. Also:
You currently use document.forms["myForm"]["fname"] and document.myForm.fname to access the same field. Pick one way and use it consistently, or
Create a variable that references the field, fname, and then use fname.value and fname.focus()
Don't bother testing for null because the .value property never will be.
Instead of immediately alerting an error and returning, add the error text to an array and then at the end test if the array is empty.
You can go with Hthml 5 required. It's so much simpler and neat.
<form>
First name: <input type="text" name="fname" required="required">
Last name: <input type="text" name="lname" required="required">
<input type="submit" value="Submit">
</form>
Demo
Note: The required attribute is supported in Internet Explorer 10, Firefox, Opera, and Chrome. But it is not supported in Internet Explorer 9 and earlier versions, or in Safari.
Try to validate your field as:
if (!x || x.length == 0)
BAsed on your validateForm function, your code would never check the second field. When using the return statement, the function will stop executing, and return the specified value.
A solution is use nested if statements and check both fields in one conditional block
if (x==null || x=="")
{
if (y==null || y=="")
{
//codes for both are not validated
}
else
{
//codes for just x is not validated
}
}
else
if (y==null || y=="")
{
//codes for y is not validated
}
else
{
//codes for all validated
}
This way use of return statement in each block won't break your function execution

JavaScript no response with validation

I am new to javascript and I am attempting to create a simple form validation. When I hit the submit button nothing happens. I have been looking at examples for a while and I cannot seem to figure out where I am going wrong. Any suggestions:
Right after this post I am going to break it all down and start smaller. But in the meantime I figured another set of eyes couldn't hurt and it is very possible I am doing something horribly wrong.
HTML:
<form name="form" action="index.html" onsubmit="return construct();" method="post">
<label>Your Name:<span class="req">*</span> </label>
<input type="text" name="name" /><br />
<label>Company Name:<span class="req">*</span> </label>
<input type="text" name="companyName" /><br />
<label>Phone Number:</label>
<input type="text" name="phone" /><br />
<label>Email Address:<span class="req">*</span></label>
<input type="text" name="email" /><br />
<label>Best Time to be Contacted:</label>
<input type="text" name="TimeForContact" /><br />
<label>Availability for Presenting:</label>
<input type="text" name="aval" /><br />
<label>Message:</label>
<textarea name="message" ROWS="3" COLS="30"></textarea>
<label>First Time Presenting for AGC?:<span class="req">*</span></label>
<input type="radio" name="firstTime" value="Yes" id="yes" /><span class="small">Yes</span>
<input type="radio" name="firstTime" value="No" id="no"/><span class="small">No</span><br /><br />
<input type="submit" name="submit" value="Sign-Up" />
</form>
JavaScript:
function construct() {
var name = document.forms["form"]["name"].value;
var companyName = document.forms["form"]["companyName"].value;
var email = document.forms["forms"]["email"].value;
var phone = document.forms["forms"]["phone"].value;
var TimeForC = document.forms["forms"]["TimeForContact"].value;
var availability = document.forms["forms"]["aval"].value;
if (validateExistence(name) == false || validateExistence(companyName) == false)
return false;
if (radioCheck == false)
return false;
if (phoneValidate(phone) == false)
return false;
if (checkValidForOthers(TimeForC) == false || checkValidForOthers(availability) == false)
return false;
if (emailCheck(email) == false)
return false;
}
function validateExistence(name) {
if (name == null || name == ' ')
alert("You must enter a " + name + " to submit! Thank you."); return false;
if (name.length > 40)
alert(name + " is too long for our form, please abbreviate."); return false;
}
function phoneValidate(phone) {
if (phone.length > 12 || phone == "" || !isNaN(phone))
alert("Please enter a valid phone number."); return false;
}
function checkValidForOthers(name) {
if (name.length > 40)
alert(name + " is too long for our form, please abbreviate."); return false;
}
function messageCheck(message) {
var currentLength = name.length;
var over = 0;
over = currentLength - 200;
if (name.length > 200)
alert(name + " is too long for our form, please abbreviate. You are " + over + " characters over allowed amount"); return false;
}
function radioCheck() {
if (document.getElementById("yes").checked == false || document.getElementById("no").checked == false)
return false;
}
function emailCheck(email) {
var atpos = email.indexOf("#");
var dotpos = email.lastIndexOf(".");
if (atpos < 1 || dotpos < atpos + 2 || dotpos + 2 >= email.length) {
alert("Not a valid e-mail address");
return false;
}
}
Am I calling my functions incorrectly? I honestly am not sure where I am going wrong.
I don't understand how to debug my code... I am using chrome and I am not receiving any errors in the console. Is there a way to set breakpoints to step through the javascript?
I realize i just threw a lot of code up there so thanks in advance for sifting through it.
Here is mistake:
Replace var email = document.forms["forms"]["email"].value;
by var email = document.forms["form"]["email"].value;
There are lot of places in your js :
var email = document.forms["forms"]["email"].value;
var phone = document.forms["forms"]["phone"].value;
var TimeForC = document.forms["forms"]["TimeForContact"].value;
var availability = document.forms["forms"]["aval"].value;
where you mistyped form as forms.
Is there a way to set breakpoints to step through the javascript?
Yes there is a way to set breakpoints:
Refer following links in order to know the method to set break-point in debugger console in Chrome:
LINK 1
LINK 2
The following should fix the immediate problem:
function construct(form) {
var
name = form["name"].value,
companyName = form["companyName"].value,
email = form["email"].value,
phone = form["phone"].value,
TimeForC = form["TimeForContact"].value,
availability = form["aval"].value
;
if (!validateExistence(name) || !validateExistence(companyName)) {
return false;
}
else if (!radioCheck) {
return false;
}
else if (phoneValidate(phone) == false) {
return false;
}
else if (!checkValidForOthers(TimeForC) || !checkValidForOthers(availability)) {
return false;
}
else if (emailCheck(email) == false) {
return false;
}
}
You had a typo in the form document.forms["forms"], where 'forms' doesn't exist. Instead of always traversing objects to get to your form, you can use this to pass the current element into your function.
<form action="index.html" onsubmit="return construct(this);" method="post">
If you're starting out it's also a good idea to make sure you set all your braces (i.e. curly brackets) as this will help you avoid getting confused with regards to alignment and brace matching.
Your first problem is the forms where you meant form. See here
But you have other problems with your validation code, for example:
if (name == null || name == ' ')
Here you are checking if name is null or name is a single space. I assume you wanted to check if the field is blank, but a completely empty string will evaluate as false in your condition, as will two spaces. What you probably want to do is something like this:
if (!name) {
// tell the user they need to enter a value
}
Conveniently (or sometimes not), Javascript interprets null, an empty string, or a string full of white space as false, so this should cover you.
You also have a whole host of other problems, see this:
http://jsfiddle.net/FCwYW/2/
Most of the problems have been pointed out by others.
You need to use braces {} when you have more than one line after an
if statement.
You need to return true when you pass you validation
tests or Javascript will interpret the lack of a return value as false.
Your radioCheck will only pass if both radio buttons are checked.
You where checking that your phone number was NOT NaN (i.e. it is a number) and returning false if it was.
I would suggest learning some new debug skills. There are ways to break down a problem like this that will quickly isolate your problem:
Commenting out code and enabling parts bit by bit
Using a debugger such as Firebug
Using console.log() or alert() calls
Reviewing your code line-by-line and thinking about what it is supposed to do
In your case, I would have first seen if name got a value with a console.log(name) statement, and then moved forward from there. You would immediately see that name does not get a value. This will lead to the discovery that you have a typo ("forms" instead of "form").
Some other errors in your code:
You are returning false outside of your if statement in validateExistence():
if (name == null || name == ' ')
alert("You must enter a " + name + " to submit! Thank you.");
return false;
In this case, you do not have brackets {} around your statement. It looks like return false is in the if(){}, but it is not. Every call to this code will return false. Not using brackets works with a single call, but I don't recommend it, because it leads to issues like this when you add additional code.
In the same code, you are using name as the field name when it is really the value of the field:
alert("You must enter a " + name + " to submit! Thank you."); return false;
You really want to pass the field name separately:
function validateExistence(name, field) {
if (name == null || name == ' ') {
alert("You must enter a " + field + " to submit! Thank you.");
return false;
} else if (name.length > 40)
alert(field + "value is too long for our form, please abbreviate.");
return false;
}
}
You are not calling radioCheck() because you are missing parentheses:
if (radioCheck == false)
In radioCheck(), you are using || instead of &&. Because at least 1 will always be unchecked by definition, you will always fail this check:
if (document.getElementById("yes").checked == false || document.getElementById("no").checked == false) return false;
And more...
My suggestion is to enable one check at a time, test it, and once it works as expected, move on to the next. Trying to debug all at once is very difficult.
replace var email = document.forms["forms"]["email"].value;
by
var email = document.forms["form"]["email"].value;
Try With Different Logic. You can use bellow code for check all four(4) condition for validation like not null, not blank, not undefined and not zero only use this code (!(!(variable))) in javascript and jquery.
function myFunction() {
var data; //The Values can be like as null,blank,undefined,zero you can test
if(!(!(data)))
{
alert("data "+data);
}
else
{
alert("data is "+data);
}
}

Login form validation using javascript and php

I have been trying to create a login form using JavaScript. My login form needs to do the following using JavaScript validation
login field contains only letters with a minimum of 4 and a maximum of 6 letters
password is at least 5 characters long and not more than 7 characters and contains only letters and digits with at least 1 letter and at least 1 digit
if the data is incorrect, generate an alert window with an appropriate
message and set the cursor to the incorrect input field and the form needs to be submitted to a php file which needs to validate against a text file
I tried to use regular expression to check for the login fields and password in the javascript and i have used a login .php but haven't done anything in that till now.However my JavaScript/HTML file which i have pasted below doesn't seem to work. Can anyone tell me the issue with my file?
<html>
<head>
<script>
function validateFormOnSubmit(theForm) {
reason += validateUsername(theForm.username.value)
reason += validatePassword (theForm.pwd.value)
if (reason == "") return true
else { alert(reason); return false }
}
function validateUsername(fld) {
if (fld == "")
return "No username entered"
else if((fld.length > 6) || (fld.length < 4 ))
return "value must be between 4 and 6 characters"
else if (/[^a-zA-z]/.test(fld))
return "only letters allowed"
}
function validatePassword (fld){
if (fld == ""){
return "No password entered";
}
else if (fld.length<5 ||fld.length>7 ) {
return "length shoild be b/w 4 and 7";
}
else if (!/[a-z]/.test(fld) || !/[A-Z]/.test(fld) || !/[0-9]/.test(fld)){
return "passwords rewuire one of the letters or digitys";
}
}
</script>
</head>
<body>
<table class ="signup" border ="o" cellpadding ="2"
cellspacing ="5" bgcolor ="eeeeee">
<th colspan="2" align="center">SignupForm</th>
<form method = "post" action ="login.php" onSubmit="return validateFormOnSubmit(this)">
<tr>
<td>Your user name:</td>
<td><input name = "username" size="35" maxlength="50" type="text"></td>
</tr>
<tr>
<td>Your Password:</td>
<td><input name="pwd" size="35" maxlength="25" type="password"></td>
</tr>
<tr>
<td> </td>
<td><input name="Submit" value="Send" type="submit" ></td>
<td> </td>
</tr>
</form>
</table>
</body>
</html>
In your validatePassword function, you're logic is messed up. You have:
else if (!/[a-z]/.test(fld) || !/[A-Z]/.test(fld) || !/[0-9]/.test(fld)){
return "passwords rewuire one of the letters or digitys";
}
Which basically says that if there isn't a lowercase letter, an uppercase letter, and a number then it fails. Group the upper and lower case letter checks into one logical grouping like so:
else if ( ( !/[a-z]/.test(fld) && !/[A-Z]/.test(fld) ) || !/[0-9]/.test(fld)){
return "passwords rewuire one of the letters or digitys";
}
Now that says as long as there is a letter (uppercase or lowercase) AND a number, then we're good on validation. You can further compress that down to something like this:
if ( !/[a-zA-Z]/.test(fld) || !/[0-9]/.test(fld)){
return "passwords rewuire one of the letters or digitys";
}
Now if you want to achieve the functionality of highlighting the field that is failing validation, you'll need to restructure your code. One way of doing that would be to do something like this:
function validateFormOnSubmit(theForm) {
var alertMsg = false,
errMsg = validateUsername(theForm.username.value);
if (errMsg !== true) {
// highlight theForm.username by changing style or class
// set focus to this field
theForm.username.focus();
alertMsg = errMsg;
}
errMsg = validatePassword(theForm.pwd.value);
if (errMsg !== true) {
// highlight theForm.username by changing style or class
// set focus to this field
theForm.username.focus();
alertMsg += errMsg;
}
if (alertMsg !== false) return true
else {
alert(alertMsg);
return false;
}
}
function validateUsername(fld) {
if (fld == "") return "No username entered"
else if ((fld.length > 6) || (fld.length < 4)) return "value must be between 4 and 6 characters"
else if (/[^a-zA-z]/.test(fld)) return "only letters allowed"
return true;
}
function validatePassword(fld) {
if (fld == "") {
return "No password entered";
} else if (fld.length < 5 || fld.length > 7) {
return "length shoild be b/w 4 and 7";
} else if (!/[a-zA-z]/.test(fld) || !/[0-9]/.test(fld)) {
return "passwords rewuire one of the letters or digitys";
}
return true;
}
Not the prettiest approach ever, but I think you get the point. Highlight the field as you wish, and notice that if there are problems with the username AND the password, then the password field is the one that gets the focus.

Categories

Resources