Go Back   CodingForums.com > :: Client side development > JavaScript programming

Before you post, read our: Rules & Posting Guidelines

Reply
 
Thread Tools Rate Thread
Enjoy an ad free experience by logging in. Not a member yet? Register.
Old 02-17-2013, 03:55 PM   PM User | #1
julescode
New to the CF scene

 
Join Date: Feb 2013
Posts: 1
Thanks: 0
Thanked 0 Times in 0 Posts
julescode is an unknown quantity at this point
Help with form validation - textarea

Hi All
I am new to Javascript and am unable to get the validation to work for the text area or comments section of my form. I got it to work for the regular text fields but for some reason it doesn't work for the text area. I also need to validate the rating area. I appreciate your help!!

Here's what I tried first:

<script type="text/javascript">

function validateForm()

{
if (document.forms[0].comments.value == "" )
{
alert("Please enter your comments.");
form[0].comments.focus();
return false;

} // end if
return true;
}

// end function validateForm

</script>


Then I did some research and found this other method. Here's the entire file:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">

<head>

<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>

<title>Julie Mazza Web Form</title>
<link rel="stylesheet" type="text/css" href="styles.css" />

<script type="text/javascript">


function validateForm()

{
var comments = document.getElementById("comments");

if ($.trim(comments.value) == '') {
alert("Please Write Your Comments");
return false;
} else {
return true;
}
}​

</script>


</head>

<body>

<div id="wrapper">
<div id="header"></div>

<h1>Sample Feedback Form</h1>

<form method="post" action="index.xhtml" onsubmit="return validateForm()" >
<fieldset>

<label>First Name:<input type="text" name="firstname" id="firstname" /></label>
<br /> <br />
<label> Last Name:<input type="text" name="lastname" id="lastname" /></label>
<br /> <br />
<label>Street Address:<input type="text" name="stradd" id="stradd" /></label>
<br /> <br />
<label>City:<input type="text" name="city" id="city" /></label>
<br /> <br />
<label>State:<input type="text" name="state" id="state" /></label>
<br /> <br />
<label>Zip:<input type="text" name="zip" id="zip" /></label>
<br /> <br />
<label>Country:<input type="text" name="Country" id="Country" /></label>
<br /> <br />
<label>Your email:<input type="text" name="FromAddress" id="FromAddress" /></label>
<br /> <br />
</fieldset>


<fieldset>

Your Comments:<textarea name="comments" id="comments" cols="40" rows="2" >
Enter your comments here </textarea>


<br /> <br />
</fieldset>

<fieldset>
Rate this site<br />
<input type="radio" name="rating" id="rating5" value="5" /> 5 - Excellent <br />
<input type="radio" name="rating" id="rating4" value="4" /> 4 - Very Good <br />
<input type="radio" name="rating" id="rating3" value="3" /> 3 - Average <br />
<input type="radio" name="rating" id="rating2" value="2" /> 2 - Below Average <br />
<input type="radio" name="rating" id="rating1" value="1" /> 1 - Poor <br />
</fieldset>

<p>
<input type="hidden" name="ToAddress" value="jmazza3@nycap.rr.com" />
<input type="hidden" name="CCAddress" value="" />
<input type="hidden" name="Subject" value="WSD: Assignment 2.2 - Web Form for Julie Mazza" />
</p>

<fieldset>

<input type="reset" value="Reset" />

<input type="submit" value="Submit" />

</fieldset>

</form>



</div>
</body>


</html>
julescode is offline   Reply With Quote
Old 02-17-2013, 07:10 PM   PM User | #2
Philip M
Supreme Master coder!

 
Philip M's Avatar
 
Join Date: Jun 2002
Location: London, England
Posts: 17,103
Thanks: 197
Thanked 2,421 Times in 2,399 Posts
Philip M has a spectacular aura aboutPhilip M has a spectacular aura aboutPhilip M has a spectacular aura about
Try this:-

Code:
<form id = "myform" onsubmit = "return validateTA()">
Your Comments:<textarea name="comments" id="comments" cols="40" rows="2" onfocus = "this.value = '' " onblur = "return validateTA()" >
Enter your comments here </textarea>
<br><br>
<input type = "submit" value = "Submit The Form">

</form>

<script type="text/javascript">

function validateTA() {
var val = document.getElementById("comments").value;  // Do not use the same word for an HTML element name/id and a Javascript variable
val = val.replace(/^\s+|\s+$/g,"");  // strip leading and trailing spaces
val = val.replace(/[^0-9a-z\s\.,;?!]/gi, "");  // strip unwanted special characters, ^ means NOT, adjust to suit
val = val.replace(/\s{2,}/g," ");  // replace multiple spaces with one space
document.getElementById("comments").value = val;   // write it back to the field
if (val.length < 8) {  // set a minimum number of characters
alert ("Please enter your comments - using a minimum of 8 characters"); // alerts are regarded as obsolete and should be used only for testing purposes.  Use DOM methods to display a message to the user.
document.getElementById("comments").focus();
return false;
}
return true;
}

</script>

Be aware that form validation of the pattern if (document.formname.formfield.value == "") - that is blank - is barely worthy of the name, and virtually useless, as even a single space, an X or a ? will return false, that is pass the validation. A proper name may only contain letters, hyphen, space and apostrophe.
Numeric values, such as zip codes, phone numbers and dates, should be validated as such. Ditto email addresses. This topic has been covered many times before in this forum.


Three is no trim() function built into Javascript - $trim() is jQuery.

Why should I do anything for posterity? What has posterity ever done for me?
Groucho Marx (1890 - 1977)
__________________

All the code given in this post has been tested and is intended to address the question asked.
Unless stated otherwise it is not just a demonstration.

Last edited by Philip M; 02-17-2013 at 07:17 PM..
Philip M is offline   Reply With Quote
Old 02-17-2013, 08:52 PM   PM User | #3
felgall
Master Coder

 
felgall's Avatar
 
Join Date: Sep 2005
Location: Sydney, Australia
Posts: 5,532
Thanks: 0
Thanked 503 Times in 494 Posts
felgall is a jewel in the roughfelgall is a jewel in the roughfelgall is a jewel in the rough
Quote:
Originally Posted by Philip M View Post
Three is no trim() function built into Javascript - $trim() is jQuery.
The latest version of JavaScript does have a trim method for Strings.

https://developer.mozilla.org/en-US/...ts/String/Trim

Even Internet Explorer supports it in the latest version of the browser - http://msdn.microsoft.com/en-us/libr...(v=vs.94).aspx
__________________
Stephen
Learn Modern JavaScript - http://javascriptexample.net/
Helping others to solve their computer problem at http://www.felgall.com/
felgall is offline   Reply With Quote
Old 02-17-2013, 11:20 PM   PM User | #4
Old Pedant
Supreme Master coder!

 
Old Pedant's Avatar
 
Join Date: Feb 2009
Posts: 23,572
Thanks: 62
Thanked 4,061 Times in 4,030 Posts
Old Pedant is a name known to allOld Pedant is a name known to allOld Pedant is a name known to allOld Pedant is a name known to allOld Pedant is a name known to allOld Pedant is a name known to all
Actually, the original code *WILL* work:
Code:
function validateForm()
{
    if (document.forms[0].comments.value == "" )
    {
        alert("Please enter your comments.");
        form[0].comments.focus();
        return false;
    } // end if
    return true;
}
But *ONLY* if you code the textarea thus:
Code:
    <textarea name="comments"></textarea>
That is. all on one line.

When you code it thus:
Code:
    <textarea name="comments">
    </textarea>
Then it *ALREADY* contains a line break character (and, if the </textarea> is not at the very start of the line, it will contain spaces)!! And so of course it will never be equal to "".

*******

I disagree with one part of Philip's advice:
Code:
val = val.replace(/\s{2,}/g," ");  // replace multiple spaces with one space
The problem with that is that \s does *NOT* mean "space"! It means "whitespace".

So that code would also replace, for example, two line breaks with a single space!

And, in <textarea>s, line breaks usually *are* considered significant and should not be changed.

On top of that, many people like to type extra spaces into text areas to improve readability of their message. So I'd just omit that line completely.

But if you must use it, then don't use \s. Just use:
Code:
val = val.replace(/ {2,}/g," ");  // there is a space before the {
__________________
An optimist sees the glass as half full.
A pessimist sees the glass as half empty.
A realist drinks it no matter how much there is.
Old Pedant is online now   Reply With Quote
Old 02-18-2013, 08:15 AM   PM User | #5
Philip M
Supreme Master coder!

 
Philip M's Avatar
 
Join Date: Jun 2002
Location: London, England
Posts: 17,103
Thanks: 197
Thanked 2,421 Times in 2,399 Posts
Philip M has a spectacular aura aboutPhilip M has a spectacular aura aboutPhilip M has a spectacular aura about
Quote:
Originally Posted by Old Pedant View Post
And, in <textarea>s, line breaks usually *are* considered significant and should not be changed.

On top of that, many people like to type extra spaces into text areas to improve readability of their message. So I'd just omit that line completely.

But if you must use it, then don't use \s. Just use:
Code:
val = val.replace(/ {2,}/g," ");  // there is a space before the {
Good point!

But I would have thought that we want to block "a (many spaces) b" which would otherwise be of sufficient length.
__________________

All the code given in this post has been tested and is intended to address the question asked.
Unless stated otherwise it is not just a demonstration.

Last edited by Philip M; 02-18-2013 at 08:28 AM..
Philip M is offline   Reply With Quote
Old 02-18-2013, 08:17 AM   PM User | #6
Philip M
Supreme Master coder!

 
Philip M's Avatar
 
Join Date: Jun 2002
Location: London, England
Posts: 17,103
Thanks: 197
Thanked 2,421 Times in 2,399 Posts
Philip M has a spectacular aura aboutPhilip M has a spectacular aura aboutPhilip M has a spectacular aura about
Quote:
Originally Posted by felgall View Post
The latest version of JavaScript does have a trim method for Strings.

https://developer.mozilla.org/en-US/...ts/String/Trim

Even Internet Explorer supports it in the latest version of the browser - http://msdn.microsoft.com/en-us/libr...(v=vs.94).aspx
I know, but that is IE10 but as Old Pedant points out, there are still plenty of people using IE5.5. And val = val.replace(/^\s+|\s+$/g,""); seems to be hardly any longer.

I am afraid that I have this eccentric idea that I need to continue support for elderly (but still extant) browsers.

The trim() method states "The characters that are removed include space, tab, form feed, carriage return, and line feed." In other words, whitespace. That was Old Pedant's point! In a textarea newlines may be significant.
__________________

All the code given in this post has been tested and is intended to address the question asked.
Unless stated otherwise it is not just a demonstration.

Last edited by Philip M; 02-18-2013 at 08:29 AM..
Philip M is offline   Reply With Quote
Reply

Bookmarks

Jump To Top of Thread


Thread Tools
Rate This Thread
Rate This Thread:

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off

Forum Jump


All times are GMT +1. The time now is 12:55 AM.


Advertisement
Log in to turn off these ads.