Text Box Validation

JavaScript and client side scripting.

Moderator: General Moderators

phppick
Forum Commoner
Posts: 57
Joined: Thu Aug 14, 2003 5:59 am

Text Box Validation

Post by phppick »

Hi,

I have got a HTML form Like below. I want to check that all textboxes to filled while submitting. note that text box are in array..

Thanks in Advance


<html>
<head>
<title>Title</title>
</head>
<body>
<form name="the_form" method="post" action="">
<table>
<tr><td><input type="submit" value="Create Record" /></td></tr>
<tr><td> </td></tr>
<tr>
<td>Text box 1</td>
<td><input type="text" value="1" name="textbox[]" /></td>
</tr>
<tr>
<td>Text box 2</td>
<td><input type="text" value="2" name="textbox[]" /></td>
</tr>
<tr>
<td>Text box 3</td>
<td><input type="text" value="3" name="textbox[]" /></td>
</tr>
</table>
</form>
</body>
</html>
ilovetoast
Forum Contributor
Posts: 142
Joined: Thu Jan 15, 2004 7:34 pm

Post by ilovetoast »

Universal form validation script. Put in a script tag inside the head tag.

Code: Select all

// &#123;&#123;&#123; Variables

/**
 * An ordered array of array of rule, error message pairs.
 * Each rule is an array of rule, attribute pairs (optional).
 * Each error message is an optional string.
 * Each form element can have multiple rule, error message pairs, such as
 * it could be required and it could have a max length. Alternatively, each
 * form element may have no rule, error message pairs.
 *
 * Regardless of the number of rule, error message pairs, each form element
 * must be represented in this array.
 *
 * @var		array
 */
var validation_definitions=
		&#1111;
			&#1111;// submit button (not always first - just first in this form)
				&#1111;
					// No validation on submit button.
				]
			],
			&#1111;// textbox&#1111;1]
				&#1111;
					&#1111;&#1111;"req"], "ERROR: You forgot item 1."]
				]
			],
			&#1111;// textbox&#1111;2]
				&#1111;
					&#1111;&#1111;"req"], "ERROR: You forgot item 2."],
					&#1111;&#1111;"minlen", 5], "ERROR: Item 2 is too short."]
				]
			],
			&#1111;// textbox&#1111;3]
				&#1111;
					// No validation on element 3.
				]
			]
		];
				
// &#125;&#125;&#125;
// &#123;&#123;&#123; handleForm()

/**
 * Customize to suit the needs of the specifc form.
 * Calls the validation functions and handling sucess and failure according to
 * specific needs
 *
 * @param	mixed	form_object			The form object as submitted.
 * @return	boolean						true on success.
 */ 
function handleForm(form_object)
&#123;
	if (validateFormElements(form_object, validation_definitions)) &#123;
		// Success
		// Customize to suit
		alert("good dog");
		
		return true;
	&#125; else &#123;
		// Failure
		// Customize to suit

		return false;
	&#125;
&#125;

// &#125;&#125;&#125;
// &#123;&#123;&#123; validateFormElements()
		
/**
 * Simultaneous loop through the form form_object and the validation_objects.
 * Each element of the form_object is checked according to the corresponding
 * element of the validation_objects array.
 *
 * @param	mixed	form_object			The form object as submitted.
 * @param	array	validation_objects	An array of arrays of rule,
 *										error message pairs.
 *										Each rule is an array of rule,
 *										attribute pairs.
 *										Each error message is an optional string.
 * @return	boolean						true on success.
 */
function validateFormElements(form_object, validation_objects)
&#123;
	for(var i = 0; i < validation_objects.length; i++) &#123;
		//DEBUG -- allows designer to recognize errors pre-deployment
		if(form_object.elements.length <= i)
		&#123;
			alert("UNDOCUMENTED FEATURE");
			return false;
		&#125;
		//END DEBUG

		for(var j = 0; j < validation_objects&#1111;i].length; j++) &#123;
			for(var k = 0; k < validation_objects&#1111;i]&#1111;j].length; k++) &#123;
				if(validateData(form_object&#1111;i], validation_objects&#1111;i]&#1111;j]&#1111;k]&#1111;0]) == false) &#123;
					alert(validation_objects&#1111;i]&#1111;j]&#1111;k]&#1111;1]);
					return false;	
				&#125;
			&#125;
		&#125;
	&#125;

	return true;
&#125;

// &#125;&#125;&#125;		
// &#123;&#123;&#123; validateData()

/**
 * The mother of all javascript form validation.
 * Validates the form_data according to the validation_rule.
 *
 * @param	mixed	form_data			The form data to validate.
 * @param	array	validation_rule		An array of rule, attribute pairs.
 * @return	boolean						true on success.
 */ 
function validateData(form_data, validation_rule)
&#123;
	// Add or remove validation rules as needed.
	// There are dozens of rules, use only the one you need.
	// Make you own rules as needed.
	switch(validation_rule&#1111;0]) &#123;
		case "req": &#123;
			if(form_data.value.length == 0) &#123;
				return false;
				break;
			&#125;
		 	break;
		 &#125;
		case "minlen": &#123;
			if(form_data.value.length < validation_rule&#1111;1]) &#123;
				return false;
				break;
			&#125;
			break;
		&#125;
	&#125;

	return true;
&#125;

// &#125;&#125;&#125;
Change your <form> tag to:

Code: Select all

<form name="the_form" action="#" method="post" onSubmit="return handleForm(this);">
Set the validation definitions to whatever you need. Add/remove validation rules as needed. Eat more toast.

Use this script for every form validation you need. I've used it for years now.

peace
ilovetoast
Forum Contributor
Posts: 142
Joined: Thu Jan 15, 2004 7:34 pm

Post by ilovetoast »

To specifically require each of the three fields just change the validation_definitions from what it is in the example to:

Code: Select all

var validation_definitions= 
       &#1111; 
          &#1111;// submit button (not always first - just first in this form) 
             &#1111; 
                // No validation on submit button. 
             ] 
          ], 
          &#1111;// textbox&#1111;1] 
             &#1111; 
                &#1111;&#1111;"req"], "ERROR: You forgot item 1."] 
             ] 
          ], 
          &#1111;// textbox&#1111;2] 
             &#1111; 
                &#1111;&#1111;"req"], "ERROR: You forgot item 2."] 
             ] 
          ], 
          &#1111;// textbox&#1111;3] 
             &#1111; 
                &#1111;&#1111;"req"], "ERROR: You forgot item 3."] 
             ] 
          ] 
       ];
You can also delete the minlen rule if you feel like it.

peace
Gen-ik
DevNet Resident
Posts: 1059
Joined: Mon Aug 12, 2002 7:08 pm
Location: London. UK.

Post by Gen-ik »

Yeah that all seems a bit long for what you want to do. On the page you are sending the form to you can check if the three variables are set using something like this...

Code: Select all

<?php

if(isset($_POST["textbox"]))
{
    $textbox = $_POST["textbox"];
    $total = 0;

    if(isset($textbox[0]) && strlen($textbox[0]) > 0) $total ++;
    if(isset($textbox[1]) && strlen($textbox[1]) > 0) $total ++;
    if(isset($textbox[2]) && strlen($textbox[2]) > 0) $total ++;

    if($total == 3)
    {
        // All fields have been filled in
    }
    else
    {
        // Some textbox info was missing
    }
}

?>
ilovetoast
Forum Contributor
Posts: 142
Joined: Thu Jan 15, 2004 7:34 pm

Post by ilovetoast »

Pros/cons:

PHP is shorter/JS is longer
PHP is server-side/JS is client-side
PHP is slower/JS is faster
PHP will have to be rewritten completely for each new form/JS won't
PHP adds to your server load/JS doesn't
PHP requires the page reload/JS doesn't

Consider this:
What happens when you let the user submit the form after filling in 2/3 fields. With PHP, you'll have to include code no just to validate as shown, but you'll also need:

Re-direct code to send them back to the page they came from to complete form.
Probable adjustments to the form itself to allow you to pass back the two completed answers -- or you force them to retype.

And every new form you write, you'll have to update all three separate code sections....

Just some thoughts.

peace
Unipus
Forum Contributor
Posts: 409
Joined: Tue Aug 26, 2003 2:06 pm
Location: Los Angeles, CA

Post by Unipus »

If it's any sort of intensive form processing with important data (membership application, order processing, etc.) you should probably validate it BOTH front-end and back-end.
Gen-ik
DevNet Resident
Posts: 1059
Joined: Mon Aug 12, 2002 7:08 pm
Location: London. UK.

Post by Gen-ik »

@ ilovetoast

Ok. But as we all know not everyone has JavaScript enabled... which would mean the form (a) wouldn't validate and (b) probably wouldn't submit. PHP on the other hand is server-side so it doesn't matter how/which/what browser the user is using.

It really doesn't take long to create PHP code which validates a form... and yes you will need to think about redirecting the user back to the form page if info is missing... but so what? Your argument sounds 'lazy' to me... creating good solid PHP code is never a quick job but it's worth it in the end.

I think that a lot of the guru-types on the forum will agree that PHP is probably the best way to go when it comes to form validation.
ilovetoast
Forum Contributor
Posts: 142
Joined: Thu Jan 15, 2004 7:34 pm

Post by ilovetoast »

Gen-ik wrote:Ok. But as we all know not everyone has JavaScript enabled... which would mean the form (a) wouldn't validate and (b) probably wouldn't submit. PHP on the other hand is server-side so it doesn't matter how/which/what browser the user is using.
This is a whole separte can of worms... the idea that users can't be expected/required to turn on javascript is a great debate in and of itself.
Gen-ik wrote:It really doesn't take long to create PHP code which validates a form... and yes you will need to think about redirecting the user back to the form page if info is missing... but so what? Your argument sounds 'lazy' to me... creating good solid PHP code is never a quick job but it's worth it in the end.

I think that a lot of the guru-types on the forum will agree that PHP is probably the best way to go when it comes to form validation.
I'm not touching this with a long stick.

Setting aside the PHP vs. javascript issue, which I believe is spurious at best, here's the point.

If you write PHP validation you are writing 3 separate code blocks in 2 different files at a minimum. Parturient montes, nascetur ridiculus mus.

Instead of separating your code from your deisgn, you're taking the approach of mixing it all together. Good luck if you make a design change that affects the form. Hope you don't miss anything in the 3 PHP blocks in the 2 files (for every form). Good luck in a collaborative environment making sure noone mucks things up.

Instead of having a function that amounts to an js include statement, a function call in the form submit, and as little as 1 other line of code (which is completely separate from the design), you end up with an intertwined mess of php and html.

peace
ilovetoast
Forum Contributor
Posts: 142
Joined: Thu Jan 15, 2004 7:34 pm

Post by ilovetoast »

And as a final comment -- this is the Client Side Forum.

dixi
Gen-ik
DevNet Resident
Posts: 1059
Joined: Mon Aug 12, 2002 7:08 pm
Location: London. UK.

Post by Gen-ik »

You've got a lot to learn about coding mate (design, not practice), but I won't push this any futher. And yes, I know this is client-side.. thank-you for pointing it out to me.
User avatar
patrikG
DevNet Master
Posts: 4235
Joined: Thu Aug 15, 2002 5:53 am
Location: Sussex, UK

Post by patrikG »

Hmm... it is a bit of a futile discussion, but PHP doing form validation = mountains wanting to give birth, but only produce a funny mouse?

Not really. Personally, I usually do my form validation in Javascript - simply because it does that client-side and, for the end-user, is thus faster.

I don't see the great complication when PHP is to do the job - when you process the data of the form, you'll need it anyway.
A simple class could easily do the form-checking and do everything else (returning to original page, showing the user which fields were missing, producing customised error-messages etc. etc.).
As Gen-ik said, once you've got that class programmed in PHP you don't need to worry about anything anymore.

Silly of me to engage in a futile discussion though. Damn.
McGruff
DevNet Master
Posts: 2893
Joined: Thu Jan 30, 2003 8:26 pm
Location: Glasgow, Scotland

Post by McGruff »

With good script design you never need to mix up php and html anywhere, ever (except maybe in a presentation layer but that's OK).

Php may not be as fast but is it fast enough..?

Php is always on. Js isn't. Therefore you must always validate server-side. Php validation is mandatory; js validation is optional. I personally wouldn't bother with the latter unless there was a need such as a multi-page set of forms with many fields.

Not writing js also saves a lot of coding given that you have to write the server side stuff anyway ;)
Abdel
Forum Newbie
Posts: 2
Joined: Sat Jan 17, 2004 7:31 am

Post by Abdel »

Checking forms with javascript is a good idea, but it's not enough if you have to check more than the availability of data in forms, for example if you want to check if the e-mail field is a valid e-mail format, or the phone Number corresponds exactly to the town the user has choosen, and so on...
I use javascript for login forms,
If you want a convenient result for you and the user, you can mix the tow solutions...
ilovetoast
Forum Contributor
Posts: 142
Joined: Thu Jan 15, 2004 7:34 pm

Post by ilovetoast »

Well, I had written something long and involved here before remembering what a wise man once told me. Never argue with a fool, people might not know the difference.

Literal latin translations.....

I answer a question promptly, accurately, and in the manner requested.... and get called everything short of m*****-bleeping-f***** for daring to give a client-side answer to a client-side question. Whatever.

Since this is now the Don't Even Consider Client Side Scripting Forum here's a link to a real PHP validator. Too many people here reinventing the wheel:

http://pear.php.net/package/Validate

Darn, guess i needed js turned on to click on the URL tag.... good thing I had that or who knows what would have happened.

To those who feel they didn't earn my sarcasm. Walk on.

peace
User avatar
patrikG
DevNet Master
Posts: 4235
Joined: Thu Aug 15, 2002 5:53 am
Location: Sussex, UK

Post by patrikG »

I answer a question promptly, accurately, and in the manner requested.... and get called everything short of m*****-bleeping-f***** for daring to give a client-side answer to a client-side question. Whatever.
Nobody called you anything. Everyone here posted their opinion dealing with the issue you raised in your answer.

If you took offense, because I said this discussion was futile, we misunderstood each other. A discussion about PHP vs Javascript is comparing trees with flowers.
Never argue with a fool, people might not know the difference.

Literal latin translations....
To those who feel they didn't earn my sarcasm. Walk on.
In all honesty: do get off that high horse of yours. We are all on an equal playing field here and are here to help.
Post Reply