Jump to content
Stef's Coding Community
fab5freddy

Form Validation

Recommended Posts

I have recently started working on form validation in my class and have gotten stuck on a few things . The first one is I am unsure how to run a test for presses of the space bar. Here is what I have so far. When I put spaces in the text box it still validates and sends the form through. This are both sections taken out of a working function just these two things do not work.

 

if (document.forms[0].artistIdNumber.value.length == "        ") {
           alert("Artist Id cannot contain spaces.");
           document.forms[0].artistIdNumber.select();
   return false;
   }   

 

Also I am having a problem testing for a positive number as well. The number needs to be greater than zero. Here is my code for that.

 

if (document.forms[0].productWeight < 0) {
       alert("Need to have a positive number");
       return false;
   }

Share this post


Link to post
Share on other sites

Im definatley not a javascript guy but this line

 

if (document.forms[0].productWeight < 0) {

 

tells me its looking for less than 0. Try < 1 or == 0

Share this post


Link to post
Share on other sites

1:

Here's a very brief demonstration: (pulled primarily from http://stackoverflow.com/questions/2031085/check-if-string-contains-characters-whitespaces-not-only-whitespaces

 

<script type="text/javascript">

function check_input()
{

if (document.form.test.value.match(/^\s+$/))
{
	alert("Artist Id cannot contain spaces.");
               document.form.test.select();
}
}

</script>

<form action="" method="post" name="form">
<input type="text" onblur="check_input()" name="test" />
</form>

 

2:

Here's a different version of your if statement that will work for negative numbers and 0

 

if (document.forms[0].productWeight <= 0) {

Share this post


Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...

×
×
  • Create New...