Click to See Complete Forum and Search --> : Validating form data on some characters
pieterh
03-12-2004, 11:21 AM
Hi,
My first post in this forum. Have used the forum several times. Good stuff!
Question ;)
In my form a visitor can fill in a value. I want the value to consist onlu numbers, a-z and the "-" sign. All other characters are illegal. Can someone help me?
I've allready got script underneath to work. Maybe I got add your sollution to it :)
<script language="JavaScript" type="text/javascript">
if (document.contactform.name_from.value=="") {
alert("You forgot to fill in your name")
return false
}
return true
}
</script>
Thanks in advance,
Pieter
steelersfan88
03-12-2004, 02:22 PM
You could easily use RegExp here, but this example doesn't:<script type="text/javascript">
function checkVals() {
var theStr = document.contactform.name_from.value
var subMit = 0
if(theStr.length == 0) {
return false;
}
for(var i=0;i<theStr.length;i++) {
if(!(checkChar(theStr.charAt(i),i))) {
return false
}
}
return true;
}
function checkChar(char,pos) {
var isOk = 0
var charsOk = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890- "
var badChar;
for(var i=0;i<char.length;i++) {
isOk = 1
for(var j=0;j<charsOk.length;j++) {
if(charsOk.charAt(j) == char.charAt(i)) {
isOk = 0
}
}
if(isOk == 1) {
alert("Invalid Character at Position #"+ (pos - -1) +"\nThe character "+ char.charAt(i) +" is illegal.\nOther errors may also exist.")
return false;
}
}
return true
}
</script>
<form name="contactform" onsubmit="return checkVals()">
Name From: <input name="name_from">
<input type="submit" value="Submit!">
</form>You might need other things ... i'm willing to help!
pieterh
03-13-2004, 07:47 AM
Thanks!
But.... ;)
When a visitor doesn't give a value, an alert message should say: "fill in name". How do I do that?
And.. if the visitor uses spaces it is also accepted. Could u give me more advice?
Cheers,
Pieter
steelersfan88
03-13-2004, 08:09 AM
Change this line:if(theStr.length == 0) {
return false;
}toif(theStr.length == 0) {
alert("Fill in Name")
return false;
}If you do not want to accept spaces, take the space out of the charsOk (space is at end and beginning). the charsOk would then look like this:var charsOk = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWX
YZ1234567890-"And just so you know, this could be done with like 3 line sof code with RegExp, but this will do fine.
pieterh
03-13-2004, 08:22 AM
Thanks for the quick reply!
All is working fine now.
Cheers,
Pieter
steelersfan88
03-13-2004, 08:53 AM
just as a response, it looks like it automatically wants to add a space before the a, this is what it should look like:var charsOk = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890-'No spaces anywhere in the ' ... ', even if they show up!
glad to help out!