View Full Version : alphanumeric check

10-14-2006, 11:58 PM
I want to check whether an input field is alphanumeric. If not the form should not be submitted. Below is the code I am using in my function..

var valid="123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
var sizechar = document.form.field.value.length;

for (var i=0; i<sizechar; i++) {
if (valid.indexOf(document.form.field.value.charAt(i)) < 0) {
alert('Your password contains invalid characters.');
return false;

The problem:
If the password is not alphanumeric I get the alert as expected. However, the form still submits. What am I doing wrong?


10-15-2006, 01:00 AM
I suspect you used something like this:

<form [...] onsubmit="validate(this)">
you need to use something like this:

<form [...] onsubmit="return validate(this)">
I suggest you learn how to use regular expressions. (http://www.regular-expressions.info/tutorial.html)

I also suggest you read these:
The Behavior Layer (http://www.digital-web.com/articles/the_behavior_layer/)
Separating behavior and structure (http://www.digital-web.com/articles/separating_behavior_and_structure_2/)
Behavioral Separation (http://www.alistapart.com/articles/behavioralseparation/)
Unobtrusive JavaScript (http://www.onlinetools.org/articles/unobtrusivejavascript/)
DOM Scripting - Sample chapter: Best Practices (http://www.domscripting.com/book/sample/)
Accessible DHTML (http://www.severnsolutions.co.uk/articles/001/)