Forum Moderators: open

Message Too Old, No Replies

slightly weird validation - question

         

patricia_e

3:10 am on Sep 6, 2004 (gmt 0)

10+ Year Member



Hello.
My superiors have a slightly odd validation need. They want end users to fill in a form. They want to let the end user know (when submit is pressed) that they have not filled out some fields if at least 1 field is left blank. However, they do not want to require them to fill it out. They just want an alert box to pop up saying to be aware that they didn't fill all the fields out. My superiors also don't want this alert box to show up when an end user has filled in all the fields. I got the code to work when I hard-coded the form element values in "if...then" statements. However, I am now trying to write a loop that is "generic" and which tests all form elements to see if something is entered (so I can reuse this code for multiple forms). I cannot get my code to work.

Any ideas?

function isBlank(testStr)
{
if (testStr.length == 0) // nothing entered?
return true
for (var i = 0; i <= testStr.length-1; i++) // all spaces?
if (testStr.charAt(i)!= " ")
return false
return true
}

function submitIt(form)
{
//alert ("Just entered the submitIt function");

// loop through each input field
for (i=0; i<form.elements.length; i++)
{
var x = form.elements[i].value;
//alert(x);

// for input field x, test to see if it's blank
if(form.elements[i].value.length == 0)
{
// if input field x is blank, set a variable y to "blank" and exit loop
//alert (x);
y = "blank";
break;
//return false
}
}

// if y is "blank", alert the user that they are leaving fields blank
if (y == "blank")
{
alert("If you have left any of the fillable form fields blank, your letter will not be complete. Please review the missing parts in the document which you may now save to your computer.");
}

return true
}

Thanks!
Patricia

Bernard Marx

4:09 pm on Sep 6, 2004 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



It's a simple process..that can have complications.
The elements collection is a 'flat' list of ALL the form's elements. This includes buttons, and <fieldset> elements (and maybe other furniture). Some of these may not have values anyway.

This one tests each element's type against a simple regular expression, before testing whether it has an entry. A regular expression is easier to extend, and is easily set to ignore case, just in case the browser returns "TEXT" for an element's type.

I have put in a custom string method for trimming whitespace from values - no need to run through the string testing if all are spaces - and also a trivial isBlank method.
Empty strings ("") evaluate to false, whilst any other input evaluates true (even "0", since it's a string) - so the function returns true for empty or all spaces.

This will need to be extended if you want to find out about whether or not radio button sets have been selected. Not only because we aren't testing for type="radio", but because the elements collection lists every single button. Extra bits are needed there to test that one has been checked.

[pre]
<html>
<head>
<title>All Filled?</title>
<script>
//*! Replace the ¦ in this RE for an unbroken pipe char.
String.prototype.trim = function(){ return this.replace(/(^\s+)¦\s+$/g,"")}
String.prototype.isBlank = function(){return!this.trim()!=""}

function submitIt(form)
{
var allFilled = true;
// could use: form.getElementsByTagName('input')
var elements = form.elements;
// create regular expression for getting
// the input types we want
// This one likes 'text' or 'textarea'
var type = /text/i;
// loop through each input field
// while loop is neater (IMHO)
var elm, k=0;
while(elm=elements[k++]){
if( type.test(elm.type) &&
elm.value.isBlank() )
{
allFilled = false;
break;
}
}

if(!allFilled)
allFilled = confirm("Not all fields were completed.\n Submit anyway?")

return allFilled
}

</script>
</head>
<body>
<form name="form" onsubmit="return submitIt(this)">
<fieldset name="fset">
<input type="text" name="one">
<input type="text" name="two">
<input type="submit">
</fieldset>
</form>
</body>
</html>
[/pre]

Cochrane

12:15 pm on Sep 7, 2004 (gmt 0)

10+ Year Member



Patricia:
Does this help?

<HTML>
<Head>
<Script Language=JavaScript>

function submitIt(isForm,btnID){

nEmpty = 0;
nFields = document.forms[isForm].length-1;
for (i=0; i<nFields; i++)
{
txtStr = document.forms[isForm][i].value;
if (txtStr == ''){nEmpty++}
blankStr = txtStr.match(/\S/);
if (blankStr == null){nEmpty++}
}
if (nEmpty!= 0)
{
alert("If you have left any of the fillable form fields blank,\nyour letter will not be complete.\nPlease review the missing parts in the document \nwhich you may now save to your computer.")
}
document.getElementById(btnID).disabled = true;
}

</Script>
</Head>
<Body>
<br><br>
<H4> Demo Form </H4>
<form name='demoForm'>
1st Field:<br>
<textarea rows=1, cols=25></textarea><br>
2nd Field:<br>
<textarea rows=1, cols=25></textarea><br>
3rd Field:<br>
<textarea rows=1, cols=25></textarea><br><br>
<input type=button value='Submit' id=submit1 onClick="submitIt('demoForm','submit1')">
</form>
</Body>
</HTML>

patricia_e

5:05 pm on Sep 7, 2004 (gmt 0)

10+ Year Member



Bernard, Cochrane,
I tried them both and they both worked... You are wonderful! So, the elements array captures things (furniture,lawn ornaments, kitchen utensils, light! ;) ) that I may not want to validate on, right? Sort of a black hole of sorts.

So if I want to use the element array, I have to tell the computer which elements to test the "blankness" of.

Bernard, in your code, you used "type.test(elm.type)". Is test a standard method? Where can I find out more about this? Also where can I find out more about your two lines of code at the top:
String.prototype.trim = function(){ return this.replace(/(^\s+)¦\s+$/g,"")}
String.prototype.isBlank = function(){return!this.trim()!=""}

This looks like OO Java code to me. I'd like to know more about using this.

Cochrane,
In your code you used:
nFields = document.forms[isForm].length-1;

Why do you use -1?

Also, you use this:
txtStr = document.forms[isForm][i].value;

[isForm] tells you which form to use and then i tells you which member of the element array?

I think that this may be where I went wrong in my own code. (I am still trying to understand why mine didn't work.)

Lastly, you use:
txtStr.match(/\S/)

How do I find out about methods like match? Where do you go to find that?

Sorry about all of the questions. I am trying to get better at this javascript stuff and it seems to continually plague me.

Thanks so much for your help!
Patricia

patricia_e

5:14 pm on Sep 7, 2004 (gmt 0)

10+ Year Member



Cochrane,
You also use a button id but I don't see it being used in the function submitIt. Is that used for something behind the scenes that I don't know about?

Again, thanks SO MUCH for your help!
:)

Cochrane

5:19 pm on Sep 7, 2004 (gmt 0)

10+ Year Member



Patricia:

In your code you used:
nFields = document.forms[isForm].length-1;
Why do you use -1?
---- Because the button is inbetweent the form tags, so it would be counted in the "length" property.

Also, you use this:
txtStr = document.forms[isForm][i].value;
[isForm] tells you which form to use and then i tells you which member of the element array?
------ Yes, if you notice, in the onClick code, I pass two values to the function: the name of the form, and the ID of the button. isForm,btnId are then in the opening declaration of the function. isForm is the name of the form.
You can access a form either with its name, or by its number. For example if your document has two forms, you can give them names, or access them like this:
document.forms[0].length, where 0, is the first form and 1 would be the second form. Or with the name: document.forms['thisName'].length. And yes, i then is the element's position in the form, with 0 again being the first element.

Lastly, you use:
txtStr.match(/\S/)
How do I find out about methods like match? Where do you go to find that?
Any JavaScript reference will have info on all the methods and properties. There are many of them on the web, free for downloading. The (/\S/), just searches the txtStr for any character that is not a space. If it finds a match it returns an array of those characters. If it finds only spaces, then it returns null. The JavaScript reference you eventully use will also have info on using Regular Expressions, (RegEx).

Glad I could be of help. Good luck with your project.

Cochrane

5:24 pm on Sep 7, 2004 (gmt 0)

10+ Year Member



Patrica:

Regarding the button ID, this line is in the function:

document.getElementById(btnID).disabled = true;

I use it to disable the Submit button, so that it can't be clicked more than once.

patricia_e

5:47 pm on Sep 7, 2004 (gmt 0)

10+ Year Member



Cochrane,

I was busy copying and pasting this code into the numerous forms pages that I have when I realized that some of the forms have a drop-down for which a choice must be chosen. All the rest of the fields are optional and I would like the form to exhibit the same behavior as described above (just alert user with a warning but let them submit and go to the next screen).

I tried altering the code like so:
function submitIt(isForm,btnID)
{
//make sure they enter a letter subject
var subjectChoice = document.theForm.subjectLetter.value;
if (subjectChoice == "")
{
alert("Please choose a subject for the letter.");
return false;
}

nEmpty = 0;
nFields = document.forms[isForm].length-1;
for (i=0; i<nFields; i++)
{
txtStr = document.forms[isForm][i].value;
if (txtStr == '')
{nEmpty++}

blankStr = txtStr.match(/\S/);
if (blankStr == null)
{nEmpty++}
}

if (nEmpty!= 0)
{
alert("If you have left any of the fillable form fields blank,\nyour letter will not be complete.\nPlease review the missing parts in the document \nwhich you may now save to your computer.")
}
}

However, this didn't work. It alerts the user if they haven't picked a choice in the drop-down but it doesn't warn them that the rest of the fields are not filled out. Should I be placing my exception code inside of the code you wrote?

Cochrane

6:49 pm on Sep 7, 2004 (gmt 0)

10+ Year Member



Patricia:

Please try this function. I added a pull-down, and a test for whether a selection has been made. It can be anywhere within the form, it doesn't have to be the first element.
Also, please note that in the onClick declaration, I added another value being passed to the function, which is the name of the select list, and this value, MUST NOT BE ENCLOSED IN QUOTES, like the other two values are.
The gist of things now is that I creat an array of the the element "numbers" that are textareas, and then use that array, the same as before to test if the textareas are blank or contain nothing but spaces.
Hope this helps.

<HTML>
<Head>
<Script Language=JavaScript>

function submitIt(isForm,btnID,selName){

nEmpty = 0;
nFields = new Array();
x = 0;
isIdx = selName.selectedIndex
if (isIdx == 0){alert('Please choose a letter style')}
else
{
nElements = document.forms[isForm].length;
for (n=0; n<nElements; n++)
{
if (document.forms[isForm][n].type == 'textarea'){nFields[x++] = n}
}
for (i=0; i<nFields.length; i++)
{
txtStr = document.forms[isForm][nFields[i]].value;
if (txtStr == ''){nEmpty++}
blankStr = txtStr.match(/\S/);
if (blankStr == null){nEmpty++}
}
if (nEmpty!= 0)
{
alert("If you have left any of the fillable form fields blank,\nyour letter will not be complete.\nPlease review the missing parts in the document \nwhich you may now save to your computer.")
}
else {document.getElementById(btnID).disabled = true}
}
}

</Script>
</Head>
<Body>
<br><br>
<H4> Demo Form </H4>
<form name='demoForm'>
<select name=select1>
<option selected> Make a selection </option>
<option value='something1'> Nice </option>
<option value='something2'> Polite </option>
<option value='something3'> Angry </option>
</select>
<br>
1st Field:<br>
<textarea rows=1, cols=25></textarea><br>
2nd Field:<br>
<textarea rows=1, cols=25></textarea><br>
3rd Field:<br>
<textarea rows=1, cols=25></textarea><br><br>
<input type=button value='Submit' id=submit1 onClick="submitIt('demoForm','submit1',select1)">
</form>
</Body>
</HTML>

Cochrane

8:23 pm on Sep 7, 2004 (gmt 0)

10+ Year Member



Patricia:
Just to clarify, if the form doesn't have a pull-down, then the code above will still work. But, I made one slight cosmetic change, so I'll re-post the edited version.

<HTML>
<Head>
<Script Language=JavaScript>

function submitIt(isForm,btnID,selName){

nEmpty = 0;
nFields = new Array();
x = 0;
isIdx = selName.selectedIndex;
if (isIdx == 0){alert('Please choose a letter style')}
else
{
nElements = document.forms[isForm].length;
for (n=0; n<nElements; n++)
{
if (document.forms[isForm][n].type == 'textarea'){nFields[x++] = n}
}
for (i=0; i<nFields.length; i++)
{
txtStr = document.forms[isForm][nFields[i]].value;
if (txtStr == ''){nEmpty++}
blankStr = txtStr.match(/\S/);
if (blankStr == null){nEmpty++}
}
if (nEmpty!= 0)
{
alert("If you have left any of the fillable form fields blank,\nyour letter will not be complete.\nPlease review the missing parts in the document \nwhich you may now save to your computer.")
}
else {document.getElementById(btnID).disabled = true}
}
}

</Script>
</Head>
<Body>
<br><br>
<H4> Demo Form </H4>
<form name='demoForm'>
Letter Style:&nbsp
<select name=select1>
<option selected> Make a selection </option>
<option value='something1'> Nice </option>
<option value='something2'> Polite </option>
<option value='something3'> Angry </option>
</select>
<br><br>
1st Field:<br>
<textarea rows=1, cols=25></textarea><br>
2nd Field:<br>
<textarea rows=1, cols=25></textarea><br>
3rd Field:<br>
<textarea rows=1, cols=25></textarea><br><br>
<input type=button value='Submit' id=submit1 onClick="submitIt('demoForm','submit1',select1)">
</form>
</Body>
</HTML>

For the life of me, I can't understand why sometimes I'm allowed to edit a previous post, and sometimes not. And I NEVER receive an email, if a reply is posted. I have to keep checking. Oh, well.

Cochrane

11:45 am on Sep 8, 2004 (gmt 0)

10+ Year Member



Patricia:
I noticed that you got rid of the code to disable the button, so I did the same. Here it is, revised again.
<HTML>
<Head>
<Script Language=JavaScript>

function submitIt(isForm,selName){

nEmpty = 0;
isIdx = selName.selectedIndex;
if (isIdx == 0){alert('Please choose a letter style')}
else
{
nElements = document.forms[isForm].length;
for (n=0; n<nElements; n++)
{
if (document.forms[isForm][n].type == 'textarea')
{
txtStr = document.forms[isForm][n].value;
if (txtStr == ''){nEmpty++}
blankStr = txtStr.match(/\S/);
if (blankStr == null){nEmpty++}
}
}
if (nEmpty!= 0)
{
alert("If you have left any of the fillable form fields blank,\nyour letter will not be complete.\nPlease review the missing parts in the document \nwhich you may now save to your computer.")
}
}
}

</Script>
</Head>
<Body>
<br><br>
<H4> Demo Form </H4>
<form name='demoForm'>
Letter Style:&nbsp
<select name=select1>
<option selected> Make a selection </option>
<option value='something1'> Nice </option>
<option value='something2'> Polite </option>
<option value='something3'> Angry </option>
</select>
<br><br>
1st Field:<br>
<textarea rows=1, cols=25></textarea><br>
2nd Field:<br>
<textarea rows=1, cols=25></textarea><br>
3rd Field:<br>
<textarea rows=1, cols=25></textarea><br><br>
<input type=button value='Submit' id=submit1 onClick="submitIt('demoForm',select1)">
</form>
</Body>
</HTML>

patricia_e

3:21 pm on Sep 8, 2004 (gmt 0)

10+ Year Member



Cochrane,
Yes, disabling the submit button was a bit awkward for me and I thought it might confuse the users.

Thanks so much for your help! I appreciate your willingness to help!