Form Validation with JavaScript

  You are currently not logged in. You can view the forums, but cannot post messages. Log In | Register

17-Oct-01 01:00
This is a forum topic for discussing the article "Form Validation with JavaScript":

http://www.elated.com/articles/form-validation-with-javascript/

Shows you how to write a script that ensures your form is filled in correctly before it's sent to your server. Great for "required fields" such as email addresses!
16-Apr-10 07:19
Hi,

I changed the code a little to invoke it with the theclicker ID, this way:

html:

<form name="form-validate" method="post" action="">
<input type="text" name="name" />
<input type="text" name="email" />
<input type="submit" name="reg" value="Done" id="theclicker">
</form>


JS:

function restValidation() {
valid = true;
if ( document.form-validate.name.value == "" )
{
alert ( "Please fill in the 'Your Name' box." );
valid = false;
}
return valid;
}

function doValidation(){
var send = document.getElementById('theclicker');
send.onclick = restValidation;
}

window.onload = doValidation;


But I was wondering if you can't do it without the "valid" stuff: this way:


function restValidation() {
if ( document.form-validate.name.value == "" )
{
alert ( "Please fill in the 'Your Name' box." );
}
}


And second, if used with the valid stuff in, shouldn't it be declared first with
var valid = true;


(I'm just a javascript beginner, but learning how to, the article was very handy !)

--
http://www.bulevardi.be
20-Apr-10 07:35
Hey bulevardi, thanks for your response.

I think if you missed out the "valid" stuff - particularly "return valid;" - then the form would always submit, even if it was invalid. You need to return false if the form is invalid so that it doesn't submit.

Declaring variables with var is optional in JavaScript; however if you don't declare a variable with var inside a function then the variable will be global, rather than local. So you're right - it would be a good idea to declare the variable with var in this case (although for small scripts it probably doesn't matter).

Hope that helps! Feel free to ask if you have any more JavaScript questions.

--
Matt Doyle, Elated
25-Apr-10 19:59
Thank you so much for this post. I was having a lot of trouble with this until I found this.
30-Apr-10 18:27
@jmlrose18: You're welcome - I'm glad the article helped.

--
Matt Doyle, Elated
02-Jun-10 12:48
You can use

onblur="validate(document.formName.fieldName.value) ;"
to can check filed in database after you complete it

--
http://redesignsoft.com/
30-Jul-10 12:06
Hi,

I want to know how can this form validations extend to check several other features such as validity of an email address, names can be only strings etc.

Thank you,
Heshan.
01-Aug-10 18:21
@heshan: Here's how to validate an email address:


function validateEmail ( f ) {
if ( isEmail ( f.email_address.value ) == false )
{
alert ( "Please enter a valid email address." );
f.email_address.select ( );
return false;
}
return true;
}

function isEmail ( string ) {
if ( string.search(/^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/) != -1 )
return true;
else
return false;
}

...

<form method="post" action="script.php" onsubmit="return validateEmail(this)"> ... </form>


--
Matt Doyle, Elated
01-Aug-10 21:03
Thanks for the coding,

But I have a problem. The email validation cannot be used with other validations. If name field is empty the system says "please enter the name", likewise all the validations are there. When this email validation code enters nothing works properly.Is there a way to handle this problem??

Heshan,
01-Aug-10 21:31
@heshan: Hard to tell without seeing your code, but you'll probably need to write a validate() function to validate all your form fields. You can then call validateEmail() from within that function. Then set validate() to be the submit event handler for the form:


<form method="post" action="script.php" onsubmit="return validate(this)"> ... </form>


If you're not that familiar with JavaScript then a jQuery plugin like this could save you a lot of time & effort:

http://docs.jquery.com/Plugins/Validation

--
Matt Doyle, Elated
01-Aug-10 21:59
This my original validation code.
Please check and see how could it change?



function Validate()
{
if (document.form1.first_name.value == '')
{
alert('Please fill in your first name!');
return false;
}
else if (document.form1.last_name.value == '')
{
alert('Please fill in your last name!');
return false;
}
else if (document.form1.email.value == '')
{
alert('Please fill in your email address!');
return false;
}

else if (document.form1.phone_number.value == '')
{
alert('Please fill in your phone number!');
return false;
}
else if (document.form1.user_type.value == '')
{
alert('Please fill in your relevant user type!');
return false;
}

else if (document.form1.username.value == '')
{
alert('Please fill in your relevant username!');
return false;
}
else if (document.form1.password.value == '')
{
alert('Please fill in your desired password!');
return false;
}



else if (document.form1.password_confirmation.value == '')
{
alert('Please fill in your password again for confirmation!');
return false;
}
else if (document.form1.password.value !=
document.form1.password_confirmation.value)
{
alert("The two passwords are not identical! "+
"Please enter the same password again for confirmation");
return false;
}

else{
alert('You are successfully registered');
}
}


......



<input type="submit" name="submit" value="Register User" onClick="return Validate();" class="attribute1" />


Thanks,
Heshan.
02-Aug-10 05:52
@heshan: Here's the general idea:


} else if ( isEmail ( document.form1.email_address.value ) == false ) {
alert ( "Please enter a valid email address." );
return false;
} else {
alert('You are successfully registered');


etc...

Also I would set Validate() as the 'submit' handler for the form, rather than the 'click' handler for your submit button. There's more than 1 way to submit a form.

--
Matt Doyle, Elated
02-Aug-10 23:43
Thank you very much, it really works perfectly..

Likewise i also want to know how can we check the validity of a name containing string characters only.


Thanks,
Heshan

[Edited by heshan on 02-Aug-10 22:44]
04-Aug-10 02:46
@heshan: You can use a regular expression for that:


} else if ( !document.form1.email_address.value.match( /^[a-zA-Z]+$/ ) ) ) {
alert ( "Please enter letters only." );
return false;
} else {
...


--
Matt Doyle, Elated
04-Aug-10 06:44
Thank you very much for your help
04-Aug-10 07:16
@heshan: No problem. Feel free to ask if you have any more questions!

--
Matt Doyle, Elated
09-Aug-10 09:59
Hi
I have a bunch of required text fields and I could not figure out how to move the cursor to the first missed required text field in the form.

Appreciate your time and help.
Thanks,
Kiran
09-Aug-10 16:01
I could figure achive focusssing on the missed field that is required. But the problem now is it works fine in FF but not in IE.
When I submit the form the first time with missed required fields, it focusses on the first but the second time I miss a field it does not focus on the field.

I tried using setTimeout , but doesn't seem to help much.

Appreciate your help.
10-Aug-10 05:27
@kirand: Can you post the URL of the form with the problem please, so we can take a look?

--
Matt Doyle, Elated
10-Aug-10 10:12
Thanks Matt.
I could make the form work.
Here'z my code:

var focusElement= new Array();
focusElement = Form.getElements(frm).findAll(function(elm){return $(elm).hasClassName('validation-failed')})
focusElement[0].focus();
focusElement[0].select();
return isValid = false;
10-Aug-10 23:49
Hi all,

This is something related with php as well as java script. If anyone can help me regarding this issue i would be very pleased.

In a particular form, i have 2 fields namely customer id and Account type. Since there are many account types it is stored as a jump menu.

There are seperate tables in my database to represent each of those accounts types. There is a seperate field in each table called account number which is auto incremented.

If i select a particular account type in my form, i want to get the account number which is relevant to that account type. For an example if i click the submit button a message should appear like
" A new ..........( relevant account type) has been successfully opened"

Any idea of how this could be done?

Thanks,
Heshan.
12-Aug-10 02:28
@kirand: We'll need to see the whole form I think! Can you post its URL?

@heshan: See http://php.net/manual/en/function.mysql-insert-id.php

--
Matt Doyle, Elated
16-Aug-10 03:32
Thanks for your link,

If we added data successfully to the database there is a message box displaying and saying " Data has been added successfully to the database".

I want to know whether the icon of the message box can be changed?
since it is a successful login........


Thanks,
Heshan.
18-Aug-10 04:52
@heshan: It depends how you're creating the message box.

If you're using JavaScript alert(), then no. If you're using something like http://jqueryui.com/demos/dialog/#modal-message then yes.

--
Matt Doyle, Elated
18-Aug-10 11:32
Then its ok. Thanks.......:-)
25-Aug-10 15:05
Hi guys,

I have a problem. Need a quick reply....I want something likes this to be done.

When i want to logged out from the system or close an account etc i want to display this message. " Are you sure you want to logged or something like" and "Yes and " No" buttons are there.

How this can be achieved??

Thanks,
25-Aug-10 20:51
@heshan: Do you mean like a confirm dialog?


var answer = confirm( "Are you sure?" );

if ( answer == true ) {
// yes
} else {
// no
}


[Edited by matt on 25-Aug-10 19:52]

--
Matt Doyle, Elated
26-Aug-10 01:23
yeah, i want a confirmation dialog box. It should be asking whether " Are you sure you want to logged out from the system."
The user has the option to select " Yes" and "No"...
26-Aug-10 21:32
@heshan: Yes the code I posted above will do that for you. However the buttons are usually called OK and Cancel, rather than Yes and No.

--
Matt Doyle, Elated
04-Sep-10 12:57
Hi

I have a site that aloows a visitor to upload an image. BUT hackers are uploaoding PHP files because it has no validation.

Can you tell me how I restrict the uploaded file to a giff or jpeg and disallow any other file type?

Many thanks
SlotsBod
04-Sep-10 23:23
@slotsbod: You can't do this with JavaScript. You need to do it in your server-side code.

--
Matt Doyle, Elated
05-Sep-10 08:01
Hi Matt

The code that I have on the upload page is below...

I have tried using the Function TestFileType (fileName, fileTypes) code from your forum.

...are you saying that the validation needs to be done in the PHP at the top of the page (where the code accepts the file and added it to my MYSQL database.)

Many thanks

= = = = = = = =

<?php
include("scripts/functions.php");
$msg='';
if ($_GET['getimage'] == '1')
{
$uploadfile = "images/upload/" . $_FILES['txtFile']['name'];
if (move_uploaded_file($_FILES['txtFile']['tmp_name'], $uploadfile))
{
$msg = $_FILES['txtFile']['name'];
}
$fields[0] = 'path';
$values[0] = makeString($msg);
insertTable('image',$fields,$values);
}
?>


<html>
<head>
<title></title>

<script language="Javascript">

function TestFileType( fileName, fileTypes )
{
if (!fileName) return;

dots = fileName.split(".");
//get the part AFTER the LAST period.
fileType = "." + dots[dots.length-1];

return ('.'+fileTypes.join(".").indexOf(fileType) != -1) ?
alert('That file is OK!') :
alert("Please only upload files that end in types: \n\n" + (fileTypes.join(" .")) + "\n\nPlease select a new file and try again.");
}

function getimage()
{
if (document.getElementById("txtFile").value == '')
{
alert("No Image Selected.");
return;
}
document.forms['Form1'].action = "getimage-new.php?getimage=1";
document.forms['Form1'].submit();
}
function body_onload()
{
if ('<?echo($msg);?>' != '')
{
window.opener.imageUploaded('<?echo($msg);?>');
window.close();
}
}
</script>

</head>

[Edited by slotsbod on 05-Sep-10 07:02]
05-Sep-10 23:03
@slotsbod:

"are you saying that the validation needs to be done in the PHP at the top of the page"

Yes. JavaScript validation is pointless for what you need, since it is trivial to circumvent. You need to validate on the server and reject the file if it's not of the right type.

--
Matt Doyle, Elated
02-Dec-10 06:36
heyy can u plzz solve dis ques

create form for sudent registration which would contain following feilds
1 first name
2 last name
3 fathers first name
4 fathers last name
5 class for registration
6 stream
7 bus student (checkbox)
8 fees
9 submit

VALIDATIONS
1 the first name of student and father should start with first letter
it should not be blank
first name and last name should not match
2 if the class is 11 or 12 the stream field should become enable
otherwise it should be disabled
3 if the class of student is 1-5 the feees feild should be filled with rs2000
6-10 rs 3000
11-12 rs 4000
4 if the student is bus student then fees = +1500
19-Jan-11 19:31
Hi Matt,

Very clear explanation. Thanks so much.

One thing I am wondering, is can the javascript code also be in the <body> of the html document? I need to put a form validation into a page where the hosted solution does not give you access to the <head> tags.

Will the form still remember the answers even if not all questions are filled in, or will it clear on the validation error message, so that the user has to start the form again?

Thanks so much for your help. I'm trying to understand submit and clear actions on form validation

--
Navi
21-Jan-11 11:42
Hello,
I have a question. How can I get the alert box to only appear once with all of the errors on it? So it would be a multi-line error box? Thank you!
23-Jan-11 20:43
@MaryBlight: Yes, if you put it towards the start of the body element then you should be OK. The validation does not clear the form.

@laisunshine: Rather than using alert()s for each field, just concatenate the error messages together into a string (separated by e.g. "\n"), then display the final string in an alert box.

--
Matt Doyle, Elated
25-Jan-11 05:07
Hi all,

I need to create an alert box in a particular time for every week. Could anyone one please tell me how is it possible ?
27-Jan-11 22:28
@asharani: Please post your question in a new topic:

http://www.elated.com/forums/authoring-and-programming/topic/new/

--
Matt Doyle, Elated
11-Feb-11 17:33
Hello guys. I had the script working as intended for more than 1 field, but I am having trouble now. I'm not the best with Javascript, so if anyone could look it over and let me know the problem, I'd appreciate it.

The address is:
http://www.shipapallet.com/requestquote2.html

As I was setting up the validation for each field, it looked like it was working as it should. When I had got down to the end, I'm thinking a character was misplaced or something, because now only the 'approximate weight' field is being validated. Any ideas?
11-Feb-11 21:13
Hi jjj84,

It's because you have lots of validate_form() functions in your code. You can't have more than 1 function with the same name in a script.

Instead, combine your checks into 1 validate_form() function, as shown in the tutorial:

http://www.elated.com/res/File/articles/development/javascript/form-validation-with-javascript/complex_form_source.html

Cheers,
Matt

--
Matt Doyle, Elated
14-Feb-11 10:43
Matt,

Thanks for the update! It works now as intended. Great script.

J.
15-Feb-11 14:28
Matt,
Thanks for your help but I am now having another issue due to a requested change on the same form.

All the validation appears to be working as it should except for on the dropdown list items. The dialog box pops up to indicate the user about the 1st dropdown they need to select, but then the form is being auto-submitted after that. The box that is popping up is for: Originating from a Residence or Business?

The link is below:
http://www.shipapallet.com/requestquote-test.html

Any idea on what is causing this issue? LIke I mentioned, I am new to Javascript so it may be something I have overlooked. Any help is appreciated.

Thanks again,
Josh J.
15-Feb-11 19:09
@jjj84: Your problem is with this line:


if ( document.sapquote.loaddock-origin.selectedIndex == 0 )


You can't use hyphens like this - JavaScript thinks you want to subtract origin from loaddock. Change your field names to not use hyphens. Alternatively (and better), use id instead of name. You can then use hyphens in your ids.

Same with loaddock-destination.

Cheers,
Matt

--
Matt Doyle, Elated
16-Feb-11 10:04
Ah ok! Got it now, works great. Thanks again!
16-Feb-11 13:44
I'm hoping you can provide me with some guidance. I have a registraion form setup with javascript validation in place, but there is one place I'm having trouble. I have a dropdown selection list, and based on the selection, there are text fields that are hidden or displayed for more info. So if you select the second item in the drop down, a text field associated with that selection appears. My issue is how to make that text field required, but only required based on drop down selection. I know there are ways to do this with radio buttons and checkboxes, but can it be done with dropdowns as well? The form is large so I didn't want to paste all here, but the snap shot of the items I'm referring to are:


<tr><td colspan=2 width="525" align="center">
<a class="form">Please let us know how you learned about us.<br></a></td></tr>
<tr>
<td colspan=2 width="525" align="center" class="form">
<select id="dropdown1" name="dropdown" onchange="display(this,'Google Search','Yahoo Search','Bing Search');" size="1" style="width:320px; font-size:11px; font-weight: bold; color: #686363;">
<option>Please select:</option>
<option value="Google Search">Google Search</option>
<option value="Yahoo Search">Yahoo Search</option>
<option value="Bing Search">Bing Search</option>
<option value="Other">Other</option>
</select>&nbsp;*
</td>
</tr>
</thead>


<tbody id="Google Search" style="display: none;">
<tr>
<td class="form" align="right"><br><br>Keywords used for search <font color="red">(Required)</font>:&nbsp;&nbsp;</td>
<td class="field"><br>
<input type="hidden" class="tbox1" id="textfield14" name="googlekey" size="40" value="-" />
<input type="text" class="tbox1" id="textfield14" name="googlekey" size="40" value="" /></td>
</tr>
</tbody>


<tbody id="Yahoo Search" style="display: none;">
<tr>
<td class="form" align="right"><br><br>Keywords used for search <font color="red">(Required)</font>:&nbsp;&nbsp;</td>
<td class="field"><br>
<input type="hidden" class="tbox1" id="textfield15" name="yahookey" size="40" value="-" />
<input type="text" class="tbox1" id="textfield15" name="yahookey" size="40" value="" /></td>
</tr>
</tbody>



Is it possible to make the the text field with name=googlekey required if some selects Google Search in drop down...but not required if they make some other selection? Thanks, David

[Edited by catron on 16-Feb-11 13:51]
20-Feb-11 19:14
@jjj84: Great stuff.

@catron: Yes, you could write something like:


if ( document.contact_form.dropdown.selectedIndex == 1 && document.contact_form.googlekey.value == "" )
{
alert ( "Please fill in the googlekey field" );
valid = false;
}


--
Matt Doyle, Elated
23-Feb-11 08:44
im having trouble with my student registration form..

if you choose the subjects BSIT, BSMATH,BSED,BEED..the year level will be limited until 4 year only while if course is BSCE,BSGE,BSArch it will limit until 5 year.. how to validate it?? can anyone help me.. thanks in advance...

<table cellpadding="10" cellspacing="10" style="text-align:left;margin-left:15em" >
<tr>
<td>User Name</td>
<td><input name="uname" type="text" id="uname" onKeyUp="isalphanum(this)" value="" size="16"/></td>
</tr>

<tr>
<td>Password</td>
<td><input type="text" name="password" value="" size="16" onKeyUp="isalphanum(this)" /></td>
</tr>
<tr>
<td>Id No. </td>
<td><input name="idno" type="text" id="idno" onkeyup="isnum(this)" value="" size="8" /></td>
</tr>
<tr>
<td>Name</td>
<td><input name="name" type="text" id="name" onkeyup="isalpha(this)" value="" size="16" /></td>
</tr>
<tr>
<td>Course</td>
<td>
<select name="course" id="course" >
<option>choose....</option>
<option value="BSIT">BSIT</option>
<option value="BSMATH">BSMATH</option>
<option value="BSED">BSED</option>
<option value="BEED">BEED</option>
<option value="BSPSYCH">BSPSYCH</option>
<option value="BLIS">BLIS</option>
<option value="BSCE">BSCE</option>
<option value="BSGE">BSGE</option>
<option value="BSArch">BSArch</option>
</select>
</td>
</tr>
<tr>
<td>Year</td>
<td><input name="year" type="text" id="year" onkeyup="isnum(this)" value="" size="8" /></td>
</tr>
</table>
28-Feb-11 04:24
@pakits: Please post your question in a new topic:

http://www.elated.com/forums/authoring-and-programming/topic/new/

--
Matt Doyle, Elated
20-Apr-11 11:05
Hi, and thanks for all of the examples. I am writing a script that validates two select menus. Could you please give me an example of how to check them one at a time and how to concatonate the errors if they exist?
25-Apr-11 03:20
@jhollender: "Validating drop-down lists" in the article shows how to check if a user has selected an option in a select menu.

To concatenate the error messages, use "+". For example:


errorMessage += "Please select your Age.\n"


--
Matt Doyle, Elated
26-Apr-11 00:15
Hi

Thanks for your codes. I am trying to validate "surname" in a form.

I need to check that it is not "empty" and if not they are alpha characters with -, space and ' special characters and with a limit of 30 chars.

The name of my form is "myForm"

I have not been able to find code anywhere that incorporates the 2 (That is, empty or alpha).

The name of the function is validateForm()
28-Apr-11 07:54
@ElizaKaye: Something like this should do what you need (I haven't tested it mind!):


if ( !document.contact_form.surname.value.match( /^[a-zA-Z- ']+$/ ) || document.contact_form.surname.value.length > 30 ) {
alert ( "Please enter your surname." );
valid = false;
}


You'll need to put that inside your validate_form() function.

Cheers,
Matt

--
Matt Doyle, Elated
06-Jul-11 11:45
Very useful. I recently stumbled across http://rindovincent.blogspot.com where i found a simple JavaScript validation form for beginners. I hope this will help some beginners.
01-Aug-11 03:51
http://www.elated.com/res/File/articles/development/javascript/form-validation-with-javascript/complex_form.html

Looking for a solution to trapping the space being entered.

[code]if ( document.contact_form.contact_name.value == "" )
{
alert ( "Please fill in the 'Your Name' box." );
valid = false;
} [code]
[]=space
In your example if one enters [] [] [] it does not trap it.

How would you stop just spaces being entered.

--
Theres always a way....
08-Aug-11 08:39
@peterfc2: Try the '===' operator instead of '=='.

--
Matt Doyle, Elated
05-Nov-11 11:44
Hi
Thanks for the information! I get my form to work with the validation, but everyone who first submits the form gets this error: "403 No variable substitutions in template"
When you reload the page the form sends perfectly. ??? I cant figure that out. www.eyefly.co.za/form.html
Please help!
07-Nov-11 00:37
@eyefly: I'm guessing you're using cgiemail to process your form on the server?

http://web.mit.edu/wwwdev/cgiemail/

This might help:

http://www.lunarforums.com/c_perl_cgi_support/cgi_error_403_no_variable_substitutions_in_template-t26554.0.html

--
Matt Doyle, Elated
07-Nov-11 00:49
Thanks for the reply - It is a cgi script: It was only after deleting my browser history that a correction in my template.txt works for me. All fine thanks for the good article.
02-Dec-11 10:18
Hi,

If I have this code :



function validation(){


valid = true;

if (document.myForm.name.value ==""){

alert("Please enter your name");
valid = false;
}
if (document.myForm.lastname.value ==""){

alert("Please enter your lastname");
valid = false;
}
if (document.myForm.address.value ==""){

alert("Please enter your address");
valid = false;
}

return valid;




How can I show all the form validation errors together in a message box ?
06-Dec-11 02:03
@Shone: Rather than using alert()s for each field, just concatenate the error messages together into a string (separated by e.g. "\n"), then display the final string in an alert box if valid == false.

--
Matt Doyle, Elated
22-Dec-11 04:44
I have a problem with my form. It has three fields which I want to validate but in testing it the first incident of validation causes the alert to pop up but then when I click OK on the alert it submits the form anyway without letting me complete the field and continue to the other fields.
It can be found at;
http://www.46thpreston.org.uk/formvalidtest.htm
18-Jan-12 20:46
Hi Matt,

I find your site very helpful.
I am an ms access guy and very new to javascript, I am trying an web application with php & mysql.

Need help for js validation in my school project.

Tablename : Table1
Feilds : Name, Class, CheckboxBook1, CheckboxBook2

Example Data:-

Name: gary Class: 1A
jane 1A
sree 1B
rita 1B
jai 1B

Validation : Each class can only select not more than 2 of Book1 and 2 of Book2

Please give me the code .

Thanking you.
08-Mar-12 17:21
Thank you for the great code! Validation is working when I test the forms but I am getting emails with 1 or -1 in fields (instead of a valid phone or email, etc.) AND I am getting 20, 40, 80 at one time.

I have tried to enter a 1 or -1 and it gives me the appropriate error message so I am not sure how I am getting these emails.

Can you give me an idea where to look / what I should do to stop these form submissions since they have gotten around the validation.

THANK YOU !!!
09-Mar-12 18:13
@tracie: Sounds like a problem with your form-to-email script running on your server, rather than a JavaScript problem.

--
Matt Doyle, Elated

 
New posts
Old posts

Follow Elated