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 01-16-2013, 06:46 PM   PM User | #1
samhor
New Coder

 
Join Date: Mar 2012
Location: USA
Posts: 30
Thanks: 0
Thanked 0 Times in 0 Posts
samhor is an unknown quantity at this point
Question How can i add some verification and required fields to this form

Hi

I have made the below form but i want to make some of the boxes etc a mandatory/required e.g. so they have to fill them in. How would i do it?

Last edited by samhor; 01-18-2013 at 01:50 AM.. Reason: mistakes
samhor is offline   Reply With Quote
Old 01-16-2013, 07:24 PM   PM User | #2
jalarie
Regular Coder

 
Join Date: Jun 2002
Location: Flint, Michigan, USA
Posts: 593
Thanks: 1
Thanked 19 Times in 19 Posts
jalarie is an unknown quantity at this point
I stripped it down to a bare minimum example and indented to make it easier to follow; you get to expand it as needed:
Code:
<script type="text/javascript">
 function CheckForm() {
  IName=document.forms[0].username.value;
  if (IName == '') {
   alert('Name is required.');
   return false;
  }
 return true;
}
</script>

<form onsubmit="return CheckForm();">
 <label for="Name">Name:</label>  
 <input type="text" name="username" size="50" />
 <input type="submit"> 
</form>
__________________
Visit my site at http://spruce.flint.umich.edu/~jalarie/.
jalarie is offline   Reply With Quote
Old 01-16-2013, 07:24 PM   PM User | #3
WolfShade
Regular Coder

 
Join Date: Apr 2012
Location: St. Louis, MO, USA
Posts: 941
Thanks: 7
Thanked 95 Times in 95 Posts
WolfShade is an unknown quantity at this point
Server-side validation is generally best (users can disable javascript - or you can force the form to submit via JavaScript, so if it's disabled the form can't submit.)

Basically, you get the value/selectedIndex of the form inputs via the DOM. Client-side validation that I like (give the form a name; change submit button to input type="button" and add onclick="return validateForm(this.form);"):
Code:
function validateForm(formObj){
var warn = "";
formObj.username.value = formObj.username.value.replace(/^\s|\s$/g,"");// trim whitespace from beginning and end of string
if(formObj.username.value.length < 5){ warn += "Please enter your Name.\n"; }
  ...
if(formObj.country.selectedIndex == 0){ warn += "Please select a Country.\n"; }
if((!formObj.choice[0].checked) && (!formObj.choice[1].checked)){ warn += "Please let us know if we can use your email for SPAMMING.\n"; }

if(warn == "") {formObj.submit(); }
else{ alert(warn); return false;}

}
__________________
^_^

If anyone knows of a website that can offer ColdFusion help that isn't controlled by neurotic, pedantic jerks* (stackoverflow.com), please PM me with a link.
*
The neurotic, pedantic jerks are not the owners; just the people who are in control of the "popularity contest".
WolfShade is offline   Reply With Quote
Old 01-16-2013, 09:30 PM   PM User | #4
felgall
Master Coder

 
felgall's Avatar
 
Join Date: Sep 2005
Location: Sydney, Australia
Posts: 5,447
Thanks: 0
Thanked 496 Times in 488 Posts
felgall is a jewel in the roughfelgall is a jewel in the roughfelgall is a jewel in the rough
Quote:
Originally Posted by WolfShade View Post
Server-side validation is generally best (users can disable javascript - or you can force the form to submit via JavaScript, so if it's disabled the form can't submit.)
Doing that would prevent those who don't have JavaScript from ever being able to submit the form. Depending on which country your visitors are in and what anti-discrimination laws apply in their country not allowing those without JavaScript to use a form may be illegal and a large fine might result.

There are some groups of disabled people who either use browsers that don't support JavaScript or where enabling JavaScript would make it impossible for them to interact with the page and such people have been known to take legal action when sites discriminate against them by not providing them with a way to interact with the site. There was one case where a large retailer whose site discriminated by requiring JavaScript that was settled out of court for a few million dollars.

Even where your site is unimportant enough to not fall foul of anti-discrimination laws, do you really want to annoy some of your visitors and have them telling all your friends how useless your site is?
__________________
Stephen
Learn Modern JavaScript - http://javascriptexample.net/
Helping others to solve their computer problem at http://www.felgall.com/

Last edited by felgall; 01-16-2013 at 09:32 PM..
felgall is offline   Reply With Quote
Old 01-16-2013, 10:26 PM   PM User | #5
samhor
New Coder

 
Join Date: Mar 2012
Location: USA
Posts: 30
Thanks: 0
Thanked 0 Times in 0 Posts
samhor is an unknown quantity at this point
Question

Hello

I have tried amending this but when adding the below it just stops working and the message doesn't pop up any more... Any ideas?

Last edited by samhor; 01-18-2013 at 01:50 AM..
samhor is offline   Reply With Quote
Old 01-16-2013, 11:45 PM   PM User | #6
jalarie
Regular Coder

 
Join Date: Jun 2002
Location: Flint, Michigan, USA
Posts: 593
Thanks: 1
Thanked 19 Times in 19 Posts
jalarie is an unknown quantity at this point
The "return true;" line belongs at the end of the function. Do all of the validation parts (name, address, ....) and their respective "return false;" lines first. If the user gets past all of those error checks, then the function returns the true value and the form submits.
__________________
Visit my site at http://spruce.flint.umich.edu/~jalarie/.
jalarie is offline   Reply With Quote
Old 01-16-2013, 11:47 PM   PM User | #7
samhor
New Coder

 
Join Date: Mar 2012
Location: USA
Posts: 30
Thanks: 0
Thanked 0 Times in 0 Posts
samhor is an unknown quantity at this point
Question Drop down menu issue

Quote:
Originally Posted by jalarie View Post
The "return true;" line belongs at the end of the function. Do all of the validation parts (name, address, ....) and their respective "return false;" lines first. If the user gets past all of those error checks, then the function returns the true value and the form submits.
Yes thanks got it working now.. How much would the code change for using drop down menus. I have tried with the below but can't seem to get it working.

Last edited by samhor; 01-18-2013 at 01:51 AM.. Reason: update
samhor is offline   Reply With Quote
Old 01-17-2013, 12:30 AM   PM User | #8
jalarie
Regular Coder

 
Join Date: Jun 2002
Location: Flint, Michigan, USA
Posts: 593
Thanks: 1
Thanked 19 Times in 19 Posts
jalarie is an unknown quantity at this point
You first pick up the index of the selected item, use that to get the "text" and "value" items, and then decide if the user has chosen something other than the default:
Code:
  SI=document.forms[0].country.selectedIndex;     // select index
  ST=document.forms[0].country.options[SI].text;  // ...on-screen text
  SV=document.forms[0].country.options[SI].value; // ...embedded value
  if (SV == "Default") { alert('Pick something'); return false; }
The "Oz", "UK", and "Usa" pieces are the "text" items and the "AUS", "UK", and "USA" pieces are the "value" items.
__________________
Visit my site at http://spruce.flint.umich.edu/~jalarie/.
jalarie is offline   Reply With Quote
Old 01-17-2013, 01:14 AM   PM User | #9
samhor
New Coder

 
Join Date: Mar 2012
Location: USA
Posts: 30
Thanks: 0
Thanked 0 Times in 0 Posts
samhor is an unknown quantity at this point
Question alert not working

[QUOTE=jalarie;1306750]You first pick up the index of the selected item, use that to get the "text" and "value" items, and then decide if the user has chosen something other than the default:
thanks

Last edited by samhor; 01-18-2013 at 01:51 AM..
samhor is offline   Reply With Quote
Old 01-17-2013, 01:15 AM   PM User | #10
felgall
Master Coder

 
felgall's Avatar
 
Join Date: Sep 2005
Location: Sydney, Australia
Posts: 5,447
Thanks: 0
Thanked 496 Times in 488 Posts
felgall is a jewel in the roughfelgall is a jewel in the roughfelgall is a jewel in the rough
Don't forget to get rid of the debugging alert() calls before you make the page live. You don't want people checking the checkbox that most broswers add to alert() to make it more useful for debugging.
__________________
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 01-17-2013, 03:57 AM   PM User | #11
samhor
New Coder

 
Join Date: Mar 2012
Location: USA
Posts: 30
Thanks: 0
Thanked 0 Times in 0 Posts
samhor is an unknown quantity at this point
Question

thanks

Last edited by samhor; 01-18-2013 at 01:52 AM..
samhor is offline   Reply With Quote
Old 01-17-2013, 08:11 AM   PM User | #12
Philip M
Supreme Master coder!

 
Philip M's Avatar
 
Join Date: Jun 2002
Location: London, England
Posts: 17,033
Thanks: 197
Thanked 2,410 Times in 2,388 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
Doing that would prevent those who don't have JavaScript from ever being able to submit the form. Depending on which country your visitors are in and what anti-discrimination laws apply in their country not allowing those without JavaScript to use a form may be illegal and a large fine might result.

There are some groups of disabled people who either use browsers that don't support JavaScript or where enabling JavaScript would make it impossible for them to interact with the page and such people have been known to take legal action when sites discriminate against them by not providing them with a way to interact with the site. There was one case where a large retailer whose site discriminated by requiring JavaScript that was settled out of court for a few million dollars.
Horsepoo. Specify an authority, please. A person of your stature ought not to propagate silly stories like that.
__________________

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.
Philip M is offline   Reply With Quote
Old 01-17-2013, 08:16 AM   PM User | #13
Philip M
Supreme Master coder!

 
Philip M's Avatar
 
Join Date: Jun 2002
Location: London, England
Posts: 17,033
Thanks: 197
Thanked 2,410 Times in 2,388 Posts
Philip M has a spectacular aura aboutPhilip M has a spectacular aura aboutPhilip M has a spectacular aura about
Quote:
Originally Posted by samhor View Post
I'm also thinking of adding an email field. How would i write the code to validate the email address e.g. an @ has been entered?
Have you tried using the search feature of this forum? That question has been asked and answered many times.

Code:
if (!(/^([a-z0-9])([\w\.\-\+])+([a-z0-9])\@((\w)([\w\-]?)+\.)+([a-z]{2,4})$/i.test(email.value))) {   /// returns true if invalid address syntax
felgall might wish to replace {2,4} by {2,6}. In reality the domains travel and museum are very rarely found. In fact, never in my experience.

Simply testing for the presence of an @ is completely inadequate. Even testing for the presence of a single @.

Another (additional?) way is to cause the user to enter his email address twice to confirm. That still does not offer complete protection, but if the user cannot get his own email address correct that is his responsibility. Nothing will prevent typos such as @gmial.com.
__________________

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; 01-17-2013 at 08:53 AM..
Philip M is offline   Reply With Quote
Old 01-17-2013, 08:25 AM   PM User | #14
Philip M
Supreme Master coder!

 
Philip M's Avatar
 
Join Date: Jun 2002
Location: London, England
Posts: 17,033
Thanks: 197
Thanked 2,410 Times in 2,388 Posts
Philip M has a spectacular aura aboutPhilip M has a spectacular aura aboutPhilip M has a spectacular aura about
Quote:
Originally Posted by samhor View Post
Yes thanks got it working now.. How much would the code change for using drop down menus. I have tried with the below but can't seem to get it working.

Code:
Icountry=document.forms[0].country.value;
  if (Icountry == '') {
   alert('Country is required.');
   return false;
  }
-----------------------------
<label for="country">Country:</label> 
  <select name="country">  
    <option selected="" value="Default">Choose a Country </option>  
    <option value="AUS">Oz</option>  
    <option value="UK">UK</option> 
    <option value="USA">Usa</option> 
  </select>
Again, have you tried using the forum search feature?

Code:
Icountry=document.forms[0].country.value;
if (Icountry == "Default") {  // the value of the first option with text Choose A Country
alert ('Country is required.');
return false;
}
-----------------------------
<label for="country">Country:</label> 
  <select name="country">  
    <option selected value="Default">Choose a Country </option>  
    <option value="AUS">Australia</option>  
    <option value="UK">UK</option> 
    <option value="USA">USA</option> 
  </select>

address=document.forms[0].address.value; // avoid using the same name for an HTML element and a Javascript variable. Always include the var keyword to make your variable local to the function.

It's a really bad idea to use NUMBERED forms. (document.forms[0])
And NAMED forms are considered obsolete.
You should give IDs to your <form> tags.

if (address == '') {
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 and phone numbers, should be validated as such. Ditto email addresses. This topic has been covered many times before in this forum.

<javascript> should be <script type = "text/javascript">


I have the idea that your grasp of Javascript at present is not really up to what you are trying to achieve.
__________________

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; 01-17-2013 at 08:54 AM.. Reason: Typo
Philip M is offline   Reply With Quote
Old 01-17-2013, 11:40 AM   PM User | #15
samhor
New Coder

 
Join Date: Mar 2012
Location: USA
Posts: 30
Thanks: 0
Thanked 0 Times in 0 Posts
samhor is an unknown quantity at this point
Question Closing js?

thanks for the info very helpful.

I have changed <script> to <script type="text/javascript">

would i still end it with <script> because </script type="text/javascript"> is an error ?

Last edited by samhor; 01-17-2013 at 11:43 AM.. Reason: submitted to quick
samhor 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 10:19 PM.


Advertisement
Log in to turn off these ads.