...

View Full Version : Limiting characters in forms



Psychoman
08-22-2004, 05:58 AM
How can I limit what type of characters a user can type inside an input field? for instance only numbers and/or characters?

]|V|[agnus
08-22-2004, 07:17 AM
<input type="text" name="input" id="input" maxlength="20" />

Psychoman
08-22-2004, 08:45 AM
thats not what I meant, I meant like only text or only numbers

jamescover
08-22-2004, 08:47 AM
How can I limit what type of characters a user can type inside an input field? for instance only numbers and/or characters?


You need to ask this in the javascript forum. Maybe, a mod will move it for you.

You can either use regular expressions, or just create a variable containing the prohibited characters, then loop through it. Something like:

Variable:

var badChar = " \/+()*&^%$#?<>=!~`[]|:;,";

Loop:

for (j=0;j<badChar.length;j++){

New variable to hold the bad character:

var illChar = badChar.charAt(j);

Conditional:

if (document['formName']['fieldName'].value.indexOf(illChar,0) !=-1){
alert("field contains illegal character(s)...!");
return false;
}
}

The statement will return -1, if no illegal character is found, so if one of the characters is found, !=-1 will evaluate to true, and produce an alert().


Together:


var badChar = " \/+()*&^%$#?<>=!~`[]|:;,";
for (j=0;j<badChar.length;j++){

var illChar = badChar.charAt(j);

if (document['formName']['fieldName'].value.indexOf(illChar,0) !=-1){
alert("field contains illegal character(s)...!");
return false;
}
}





-james

Psychoman
08-22-2004, 08:47 PM
Sorry, I didnt think that was javascript, I'm doing the form in PHP using HTML tables and such to display it, Your solution is closer to what I wasnt, however I rather not allow those characters at all as they happen.

ie. if a user presses a number, on a field that does not allow them, the key pressed would be ignored.

jamescover
08-23-2004, 12:03 AM
ie. if a user presses a number, on a field that does not allow them, the key pressed would be ignored

Well, I'm sure there's a better way to do it, but this works:


<script type="text/javascript">
<!--


function chkFrm(){
var badChar = " /\\+()*&^%$#?<>=!~`[]|:;,'";
var doc = document['oFrm']['oTxt'];

for (j=0;j<badChar.length;j++){
var illChar = badChar.charAt(j);
if (doc.value.indexOf(illChar,0) !=-1){
doc.value = doc.value.slice(illChar,-1);
}
}
}

//-->
</script>

<form name="oFrm">
<input name="oTxt" type="text" size="15" maxlength="15" onkeydown="javascript:chkFrm();" onkeyup="javascript:chkFrm();" />
</form>

I added onkeydown, so that someone can't hold down the wrong key and override the functionality.

Maybe, somebody else will chime in, and edumacate me as to the proper way...?



-james

Psychoman
08-23-2004, 12:13 AM
hmm, that looks like it might work, I'm about to test it now, Thanks :)

Psychoman
08-23-2004, 05:20 AM
Well, believe it or not, that didnt work for me, also I would have to create a whole function for each field, which is not good considering i have 20 somewhat fields.

Psychoman
08-23-2004, 05:31 AM
I found this, but only works on IE, any ideas for netscape?


<script>
function filterInput(e) {
// Get the regular expression to test against for this particular object
regAllow = (e)?eval(e.allow):eval(event.srcElement.allow);
// Check for an allowed character, if not found, cancel the keypress's event bubbling
if (!String.fromCharCode(event.keyCode).match(regAllow)) event.returnValue=false;
}
</script>

jamescover
08-23-2004, 06:01 AM
Well, believe it or not, that didnt work for me, also I would have to create a whole function for each field, which is not good considering i have 20 somewhat fields.

You didn't say what didn't work, i.e., js errors, etc., or what browser it didn't work in. I tested it (and it worked) in IE6.0 & Firefox/0.9.3


Well, believe it or not, that didnt work for me, also I would have to create a whole function for each field, which is not good considering i have 20 somewhat fields.

You've didn't previously indicate how many fields you would be using.


How can I limit what type of characters a user can type inside an input field? for instance only numbers and/or characters?


You can loop through all form fields, type "text", checking for illegal characters.



-james

jamescover
08-23-2004, 06:31 AM
I found this, but only works on IE, any ideas for netscape?

What version of NS?

The last time I did this (js 1.2/3), you had to test for the event, and capture it:


Something like:

captureEvents(eventType)

event.which ==


-james

Willy Duitt
08-23-2004, 10:38 AM
Try this:



<script type="text/javascript">
function check(input){
if(input.value.match(/\W+/g)){
alert('You may only enter a-z, A-Z or 0-9 in this field!');
input.value = input.value.replace(/[^\w]*/g,'');
input.focus();
}
}
</script>
</head>

<body>
<form>
<input type="text" onkeyup="check(this)" onchange="check(this)">
</form>


.....Willy

Edit: Added input.onfocus() to the function to return focus to the correct field if the onchage event was fired....

]|V|[agnus
08-23-2004, 04:39 PM
(D'oh! Wasn't paying attention... ;p)

jamescover
08-23-2004, 09:17 PM
<script type="text/javascript">
function check(input){
if(input.value.match(/\W+/g)){
alert('You may enter a-z, A-Z or 0-9 in this field!');
input.value = input.value.replace(/[^\w]*/g,'');
}
}
</script>
</head>

<body>
<form>
<input type="text" onkeyup="check(this)" onchange="check(this)">
</form>


bravo :thumbsup:

Psychoman
08-24-2004, 02:59 AM
Sorry jamescover, Ive been rather absent minded lately working long days to get this site finnished. The script Willy Duitt posted works awesome, but how could I change values I want to allow?

I need ones to only allow
0-9 " "(space) and "-"
and some only to allow numbers,

I'm sorry if this is something I should know, I just have more of a feel for PHP and even there I cant say I know alot.

Thanks for your patience, I should try to get a good long sleep tonight.

]|V|[agnus
08-24-2004, 06:14 AM
<script type="text/javascript">
function check(input){
if(input.value.match(/[-0-9\s]+/g)){
alert('You may 0-9,-, or spaces in this field!');
input.value = input.value.replace(/[^\-0-9\s]*/g,'');
}
}
</script>


I'm not sure if I got his replace code properly converted, as I've not used that function myself, but comparing the two uses of regular expressions, I think this is what you want.

Willy Duitt
08-24-2004, 06:38 AM
Magnus's regular expression certainly answers your latest question but my take on your latest change is that you have multiple fields which will use various validation.... some numbers only, some numbers and text and others numbers, spaces and hyphens....

If you are somewhat familar with regular expressions you can use this example and pass the expression thru the function as an arguement.... However, this is not very intuitive and not intended for the faint in heart (but is short and too the point)...



<script type="text/javascript">
<!--//
function check(input,regex){
if(input.value.length > 0 && !input.value.match('/^['+regex+']$/g','')){
input.value = input.value.replace(new RegExp('[^'+regex+']*','g'),'');
input.focus();
}
}
//-->
</script>
</head>

<body>
<form>
Numbers Only: <input type="text" onkeyup="check(this,'0-9')" onchange="check(this,'0-9')"><br>

Numbers and Text: <input type="text" onkeyup="check(this,'0-9\\w')" onchange="check(this,'0-9\\w')"><br>

Numbers Plus Spaces & Hyphen: <input type="text" onkeyup="check(this,'0-9\\s\\-')" onchange="check(this,'0-9\\s\\-')"><br>
</form>


Or, somewhat more intuitive and more easily modified....



<script type="text/javascript">
<!--//
function check(input,regex){
if(regex && input.value.length > 0){
if(regex.match(/numbersPlus/i) && !input.value.match(/^[0-9\s\-]+$/g)){
alert('You may only enter 0-9, spaces or hyphens in this field!');
input.value = input.value.replace(/[^0-9\s\-]*/g,'');
input.focus();
}

if(regex.match(/numbersOnly/i) && !input.value.match(/^[0-9]+$/g)){
alert('You may only enter 0-9 in this field!');
input.value = input.value.replace(/[^0-9]*/g,'');
input.focus();
}

if(regex.match(/numbersText/i) && !input.value.match(/^[^\W]+$/g)){
alert('You may only enter a-z, A-Z or 0-9 in this field!');
input.value = input.value.replace(/[\W]*/g,'');
input.focus();
}
}
}
//-->
</script>
</head>

<body>
<form>
Numbers Only: <input type="text" onkeyup="check(this,'numbersOnly')" onchange="check(this,'numbersOnly')"><br>

Numbers and Text: <input type="text" onkeyup="check(this,'numbersText')" onchange="check(this,'numbersText')"><br>

Numbers Plus Spaces & Hyphen: <input type="text" onkeyup="check(this,'numbersPlus')" onchange="check(this,'numbersPlus')"><br>
</form>


.....Willy

Willy Duitt
08-24-2004, 06:55 AM
BTW: Magnus;

Just a few changes....
Your conditional is missing a not (!) operator... As in does not match the expression....

Your expression also should include the start string (^) and end of string ($) and the hyphen should be escaped (\)....

And FWIW the ^ within the character class tells the browser to ignore those characters....




<script type="text/javascript">
function check(input){
if(!input.value.match(/^[\-0-9\s]+$/g)){
alert('You may 0-9,-, or spaces in this field!');
input.value = input.value.replace(/[^\-0-9\s]*/g,'');
}
}
</script>
</head>

<body>
<form>
Numbers, Spaces and Hyphens: <input type="text" onkeyup="check(this)" onchange="check(this)"><br>
</form>


Hope that helps;

.....Willy

]|V|[agnus
08-24-2004, 07:35 AM
Yeah, actually, I had copied and pasted from a previous post (http://codingforums.com/showpost.php?p=228371&postcount=12) :thumbsup: , and had in fact made those exact changes myself. I decided to change them back assuming for some reasont that there was something I wasn't understanding with the regexp. The missing not operator I thought an obvious oversight on your part, but left it anyways. I was trying too hard to be non confrontational, if you can believe it...

Willy Duitt
08-24-2004, 07:46 AM
Aye, we are both just learning regular expressions but I probably have a month or so on you...

But the missing not operator in my function was not an oversight.... If you look closely I used an uppercase W character class in the match while I removed lower case w charcter class in the replace... One is the opposite of the other....

IE:


\w Matches any word character. Equivalent to the Unicode character categories [\p{Ll}\p{Lu}\p{Lt}\p{Lo}\p{Nd}\p{Pc}]. If ECMAScript-compliant behavior is specified with the ECMAScript option, \w is equivalent to [a-zA-Z_0-9].

\W Matches any nonword character. Equivalent to the Unicode categories [^\p{Ll}\p{Lu}\p{Lt}\p{Lo}\p{Nd}\p{Pc}]. If ECMAScript-compliant behavior is specified with the ECMAScript option, \W is equivalent to [^a-zA-Z_0-9].


Cheers;
.....Willy

]|V|[agnus
08-24-2004, 07:52 AM
Ah, true! I haven't used escapes for character classes much so I'm not as savvy. I started using [:alnum:] and [:digits:] and the like until I learned that they were not as universal as I'd initially suspected. From what I'd gathered, "writing them out" (i.e. [a-zA-Z0-9_] instead of \w) seems like the best way to ensure consistency between languages, but I dunno?

Psychoman
08-24-2004, 05:32 PM
Heh, well I try to avoid using javascript because of not knowing much about it, but I can assure you I can make sense of code, its just that lookimg trough goole to find what /\W+/g meant and how i could change it was impossible, you try it and see what I mean :)

Thanks Willy Duitt for that last poste explaining what it meant, that was the only thing I couldnt figure out, as for expressions I may have used them before on other javascripts and not notice, however reading the source I can start keeping track of what it all means.

Thanks again to all of you for your help:)

Willy Duitt
08-24-2004, 05:38 PM
Here... This may help....
Regular Expression Cheatsheet (http://www.regexlib.com/CheatSheet.htm)....

.....Willy

Psychoman
08-24-2004, 09:03 PM
:eek: THAT PAGE IS AWESOME!!! THANK YOU SO MUCH!!! :thumbsup:



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum