Forum Moderators: open

Message Too Old, No Replies

JavaScript numeric input validation

Validation not working

         

TheKG

9:50 pm on May 17, 2009 (gmt 0)

10+ Year Member Top Contributors Of The Month



I need to validate that when a user enters numbers into a field that it is a number greater than 48 AND divisible by 6. I searched this forum, found this script and used it for a start:

<script type="text/javascript">
<!--
function check6(obj){
//use the modulus operator '%' to see if there is a remainder
if(obj.value%6!=0){
alert('The number you entered is not divisible by 6')
}
}
//-->
</script>

The rest of the instructions in that post was to place:

onchange='check6(this)'

in the form to let the script know what to check. I placed it at the end of the <input=> statement.

I use an image for my submit button. If the image button is clicked, the user does get the message, but if it is pressed a second time, or if the user uses the "enter" key instead, the condition is ignored and any number can be entered in the field.

What am I doing wrong?

Fotiman

2:43 pm on May 18, 2009 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



1. Remove the HTML comments from within your script tag. They don't do anything but muck up your code.

2. Ideally, you should put JavaScript in it's own file (not in your HTML file).

3. You should perform your validation in the form's onsubmit event instead of the onchange event of the input. To prevent the form from submitting, return false to the form's onsubmit handler.


function check6(obj) {
// use the modulus operator '%' to see if there is a remainder
if (obj.value % 6 != 0) {
alert('The number you entered is not divisible by 6');
return false;
}
return true;
}
// Attach your form's onsubmit handler
var f = document.getElementById('yourform');
f.onsubmit = function() {
var el = document.getElementById('yourinput');
return check6(el);
};

And in your form:


<form id='yourform' ...>
<input id='yourinput' ...>

Note, this script needs to be called after your form elements are defined. At the end of your document, just before the closing </body> tag is the best place to put your scripts (and like I said, linking to an external .js file is the best method).

Hope this helps.

TheKG

5:55 pm on May 18, 2009 (gmt 0)

10+ Year Member Top Contributors Of The Month



Thank you for the info and suggestion. I have created an external .js file. I am now not certain where the "form id" and "input id" are to go in my form. The form is to order merchandise and place it in the customer's cart. I subscribe to a 3rd party cart program and they have provided the script necessary for performance. Is the "form id" to be placed somewhere in 'action=', 'method=', or is it to be associated with the image clicked to "Add all items to cart"? I am also guessing that the <input id=> means I need to give the 'input' an id number/name for the field(s) that I need validated.

Sorry if I seem confused, but I am aware that if I put this in the wrong place, it won't work.

Thank you.

Fotiman

8:56 pm on May 18, 2009 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



You should have a form element on the page. It begins with an opening <form> tag and ends with the closing </form> tag. It will have a number of attributes defined in the opening tag (like action and method). The id is another attribute. So if your opening form tag looks like this:

<form action='...' method='...'>

You will want to add the id like this:

<form id='SOMEUNIQUEVALUE' action='...' method='...'>

Whatever value you put in place of SOMEUNIQUEVALUE is up to you, but:
1. It must be unique. There can't be any other elements on the page with the same id.
2. It must start with a letter (it can't start with a number).

The same rules apply to the id attribute you give to input element. You shouldn't have to do anything with regards to the image/submit button.

Notice in my script the code that does this:


var f = document.getElementById('yourform');

This is finding an element on the page that has the id value of 'yourform' (you will replace this with whatever unique value you choose for your form id). Likewise, this bit:

var el = document.getElementById('yourinput');

Is finding an element with the id 'yourinput' (and you'll replace that with whatever unique id you assign to your text field).

Make sense?

TheKG

9:08 pm on May 18, 2009 (gmt 0)

10+ Year Member Top Contributors Of The Month



Thank you so much! Works like a charm. Now that the user is limited to quantities evenly divisible by 6, what magic code will also limit them to entering numbers equal to or greater than 48 while still being evenly divisible by 6.

Fotiman

1:18 am on May 19, 2009 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month




function check48(n) {
return n >= 48;
}
function check6(n) {
// use the modulus operator '%' to see if there is a remainder
if (n % 6 != 0) {
alert('The number you entered is not divisible by 6');
return false;
}
return true;
}
// Attach your form's onsubmit handler
var f = document.getElementById('yourform');
f.onsubmit = function() {
var el = document.getElementById('yourinput');
return (check6(el.value) ¦¦ check48(el.value));
};

Note, I've changed the input of the check6 function to take a value instead of an object (no need to pass an element around, just the value).
Also note, this forum replaces the pipe character with ¦ so be sure to replace those characters with real pipe characters in your script.

DrDoc

1:51 am on May 19, 2009 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Also, as a side note -- please make sure you have all this validation in place on the server side as well ;)

TheKG

3:08 pm on May 19, 2009 (gmt 0)

10+ Year Member Top Contributors Of The Month



Thanks again. I updated the code; no number lower than 48 can be entered, but if a number higher than 48 is entered and is not divisible by 6, the message is displayed, however if the user continues to click "Add to Cart" or the "enter" key, the items are added to their cart anyway.

Also...your message about validating on the server side. I use Hostmonster to host the web site on their servers and a 3rd party Cart service to process the orders. (If I can't completely understand design of a page yet...don't even want to try PCI compliance :o) Is there code that I need on my page for additional validation?

Fotiman

4:37 pm on May 19, 2009 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



Oh yes, my mistake. Change this line:

return (check6(el.value) ¦¦ check48(el.value));

to this:

return (check6(el.value) && check48(el.value));

The former would return true if either condition evaluated to true, but the later will only return true if both conditions evaluate to true.

TheKG

5:16 pm on May 19, 2009 (gmt 0)

10+ Year Member Top Contributors Of The Month



Works better now. Customer still gets a message if the number they ordered meets the criteria (i.e. 60,72), but if they try again, it will be added to the cart. Any way to get around that?

Also, what about the server side validation; is there something I need to do there?

Fotiman

7:48 pm on May 19, 2009 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



Note, if you've attached the event to your form onsubmit handler instead of the onchange handler of the input, then every time they try it would perform the validation and prevent the form from submitting, so I'm wondering if you don't have it properly attached to your form submit event?

TheKG

8:35 pm on May 19, 2009 (gmt 0)

10+ Year Member Top Contributors Of The Month



OK...this one was my mistake. In my first post, I mentioned that I placed: onchange='check6(this)' at the end of my <input=> statement. You guessed it...I forgot all about it and didn't take it out. Removed it and it's PERFECT!

Now...about the server side validation. Do I need to do anything further?

BTW...you folks are awesome! I've left questions in other forums and either received no answer or some sarcastic response like I was a total idiot. The fact that my inquiries have not only been answered, but answered thoroughly with explanations, makes this the best forum for all my web design questions. Thanks to all!

Fotiman

1:42 pm on May 20, 2009 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



As for the server side validation, you would probably be better off asking those questions in a forum dealing with your particular server side language. Perhaps the PHP forum [webmasterworld.com]?

TheKG

6:39 pm on May 29, 2009 (gmt 0)

10+ Year Member Top Contributors Of The Month



Have a new problem with this. I am using PHP and MySql to populate the information on my form. Users have the option of ordering specific quantities of an item using a check box, or they may enter a quantity in a text box.

The jscript was to validate the number put in the textbox and worked fine when I was testing only one item on the page. Now that I have populated the page with all colors available, none of the checkboxes will function and only the first text box will function.

If there is more than one text box on a page, does each text box need a unique id for jscript validation to work? Can the jscript var el contain more than one id?

Thank you.

Fotiman

11:09 pm on May 29, 2009 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



Yes, id must be unique. No, elements can not contain more than one id. Give each element a unique id and change your code to check each id:

f.onsubmit = function() {
var el = document.getElementById('yourinput');
if (!check6(el)) {
return false;
}
el = document.getElementById('anotherinput');
if (!check6(el)) {
return false;
}
// Repeat for each id ...
// ...
// if made it without returning false, then all are valid
return true;
};

TheKG

7:04 pm on May 30, 2009 (gmt 0)

10+ Year Member Top Contributors Of The Month



Thanks. Revised my code and script so each text box has a different "id". All the check boxes now function properly, but the input in the text box is not validated. Here's a sample of the script:

[script]
function check48(n) {
return n &gt;= 48;
}

function check6(n) {
// use the modulus operator '%' to see if there is a remainder
if (n % 6 != 0) {
alert('Order by half-dozen increments greater than 48');
return false;
}

return true;
}
// Attach your form's onsubmit handler
var f = document.getElementById('erb');

f.onsubmit = function() {
var el = document.getElementById('BLK');
if (!check6(el.value) &amp;&amp; !check48(el.value)){
return false;
}
el = document.getElementById('BKPIN');
if (!check6(el.value) &amp;&amp; !check48(el.value)){
return false;
}
el = document.getElementById('BWCHS');
if (!check6(el.value) &amp;&amp; !check48(el.value)){
return false;
}
el = document.getElementById('BLST');
if (!check6(el.value) &amp;&amp; !check48(el.value)){
return false;
}
return true;
}
[/script]

What have I done incorrectly?

TheKG

8:44 pm on May 30, 2009 (gmt 0)

10+ Year Member Top Contributors Of The Month



In my previous post, I noticed that the program I used to open the file changed some symbols and it was too late to edit the post.

Here is the corrected code:

function check48(n) {
return n >= 48;
}

function check6(n) {
// use the modulus operator '%' to see if there is a remainder
if (n % 6 !== 0) {
alert('Order by half-dozen increments greater than 48');
return false;
}

return true;
}
// Attach your form's onsubmit handler
var f = document.getElementById('erb');

f.onsubmit = function() {
var el = document.getElementById('BLK');
if (!check6(el.value) && !check48(el.value)){
return false;
}
el = document.getElementById('BUR');
if (!check6(el.value) && !check48(el.value)){
return false;
}
el = document.getElementById('DEN');
if (!check6(el.value) && !check48(el.value)){
return false;
}
el = document.getElementById('HUN');
if (!check6(el.value) && !check48(el.value)){
return false;
}
return true;
};

TheKG

6:26 pm on Jun 1, 2009 (gmt 0)

10+ Year Member Top Contributors Of The Month



After testing and retesting, the jscript seems to be limiting the user to numbers higher than 48, but ANY number; not just those evenly divisible by 6. Can anyone please give me another suggestion? Thank you.

Fotiman

5:05 pm on Jun 3, 2009 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



In the code above, each conditional check will only be true (which steps into the return false statement) if the check6 returns false AND the check48 returns false.

Here I'll break down 4 examples, using values 6, 7, 60, 61:

if (!check6(6) && !check48(6))
if (!true && !false)
if (false && true)
if (false)

if (!check6(7) && !check48(7))
if (!false && !false)
if (true && true)
if (true)

if (!check6(60) && !check48(60))
if (!true && !true)
if (false && false)
if (false)

if (!check6(61) && !check48(61))
if (!false && !true)
if (true && false)
if (false)

As you can see, only the case that failed both of your validation functions (7) returned true.

You could fix this in one of two ways.
1. Move your logical NOT (!) operator:
if (!(check6(el.value) && check48(el.value))){

2. Change the && to an ¦¦
if (!check6(el.value) ¦¦ !check48(el.value)){

Here are the 4 examples again using these changes.

if (!(check6(6) && check48(6)))
if (!(true && false))
if (!(false))
if (true)

if (!(check6(7) && check48(7)))
if (!(false && true))
if (!(false))
if (true)

if (!(check6(60) && check48(60)))
if (!(true && true))
if (!(true))
if (false)

if (!(check6(61) && check48(61)))
if (!(false && true))
if (!(false))
if (true)

As you can see, all of the validation should work correctly. The && condition verifies that all of the individual tests passed, and then the ! converts the result (since this is checking if the validation did NOT pass).

Now the other approach:
if (!check6(6) ¦¦ !check48(6))
if (!true ¦¦ !false)
if (false ¦¦ true)
if (true)

if (!check6(7) ¦¦ !check48(7))
if (!false ¦¦ !false)
if (true ¦¦ true)
if (true)

if (!check6(60) ¦¦ !check48(60))
if (!true ¦¦ !true)
if (false ¦¦ false)
if (false)

if (!check6(61) ¦¦ !check48(61))
if (!false ¦¦ !true)
if (true ¦¦ false)
if (true)

This approach is really saying if any of the individual tests did NOT pass. Both of these methods will work for you, so choose whichever you will best be able to understand if you look at it later on.

TheKG

6:43 pm on Jun 3, 2009 (gmt 0)

10+ Year Member Top Contributors Of The Month



Tried both of these:

1. Moved the logical NOT (!) operator:
if (!((check6(el.value) && check48(el.value))){

2. Changed the && to an ¦¦
if (!check6(el.value) ¦¦ !check48(el.value)){

Each does work, but only on the first input field (id='BLK'); also, none of the checkboxes on the page work when I use either of these.

Fotiman

7:55 pm on Jun 3, 2009 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



Can you post a snippet of your HTML that shows some of the other input fields and checkboxes? Is it possible that you do not have unique id attributes on your inputs?

TheKG

8:06 pm on Jun 3, 2009 (gmt 0)

10+ Year Member Top Contributors Of The Month



The checkboxes do not have an id; each of the text boxes that I want validated do have a unique id. I did not feel comfortable posting the html here; sent it via pm.