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 00: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 06: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 06: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 - Helping people make websites since 1997!
http://www.elated.com/
25-Apr-10 18:59
Thank you so much for this post. I was having a lot of trouble with this until I found this.
30-Apr-10 17:27
@jmlrose18: You're welcome - I'm glad the article helped.

--
Matt Doyle
ELATED - Helping people make websites since 1997!
http://www.elated.com/
02-Jun-10 11: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 11: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 17: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 - Helping people make websites since 1997!
http://www.elated.com/
01-Aug-10 20: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 20: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 - Helping people make websites since 1997!
http://www.elated.com/
01-Aug-10 20: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 04: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 - Helping people make websites since 1997!
http://www.elated.com/
02-Aug-10 22: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 01: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 - Helping people make websites since 1997!
http://www.elated.com/
04-Aug-10 05:44
Thank you very much for your help
04-Aug-10 06:16
@heshan: No problem. Feel free to ask if you have any more questions!

--
Matt Doyle
ELATED - Helping people make websites since 1997!
http://www.elated.com/
09-Aug-10 08: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 15: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 04:27
@kirand: Can you post the URL of the form with the problem please, so we can take a look?

--
Matt Doyle
ELATED - Helping people make websites since 1997!
http://www.elated.com/
10-Aug-10 09: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 22: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 01: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 - Helping people make websites since 1997!
http://www.elated.com/
16-Aug-10 02: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 03: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 - Helping people make websites since 1997!
http://www.elated.com/
18-Aug-10 10:32
Then its ok. Thanks.......:-)
25-Aug-10 14: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 19: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 - Helping people make websites since 1997!
http://www.elated.com/
26-Aug-10 00: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 20: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 - Helping people make websites since 1997!
http://www.elated.com/
04-Sep-10 11: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 22:23
@slotsbod: You can't do this with JavaScript. You need to do it in your server-side code.

--
Matt Doyle
ELATED - Helping people make websites since 1997!
http://www.elated.com/
05-Sep-10 07: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 22: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 - Helping people make websites since 1997!
http://www.elated.com/

 
New posts
Old posts

Follow Elated