View Full Version : HTML Form Validation two words

07-09-2011, 12:32 AM
I want to validate via javascript an input text box. What i want is to have at least two words ( not letters ).

At this moment i did validation to detect if the input is empy:

function validateForm()
var x=document.forms["myForm"]["s"].value
if (x==null || x=="")
alert("Nu ati introdus nimic.");
return false;

But how to validate to have at leat two words inside my input area.

Thank you.

Here is my form:

<form name="myForm" method="get" id="searchform" onsubmit="return validateForm()" action="<?php bloginfo('home'); ?>/">
<div><input type="text" value="" name="s" id="s" />
<input type="hidden" name="cat" value="19" />
<input type="submit" id="searchsubmit" value="Cauta document" />

Old Pedant
07-09-2011, 01:42 AM
Maybe like this:

function validateForm(form)
var x = form.s.value;
x = x.replace(/^\s+/,"").replace(/\s+$/,""); // this trims off leading & trailing spaces
x = x.replace(/\s{2,}/," "); // this gets rid of multiple spaces
var words = x.split(" "); // split the result apart on any remaining space
if ( words.length < 2 )
alert("Must enter at least 2 words");
return false;
return true; // do not forget this

<form method="get" onsubmit="return validateForm(this)" action="<?php bloginfo('home'); ?>/">

There is no reason to give your <form> either a name or id.

And there is usually no reason to give form fields an id.

07-09-2011, 12:13 PM
unfortunately does not work.

Another option if you can ....

Thank you

low tech
07-09-2011, 01:42 PM

unfortunately does not work.

Sure it works.

What i want is to have at least two words ( not letters ).

In your opinion, what would be the minimum amount of letters contained in any two meaningful words you might expect someone to input that you will accept?