PDA

View Full Version : Validating a form field so only alpha characters can be entered



Apr 9th, 2008, 05:27 PM
Hi,

I am trying to only allow a person to enter alpha characters in this field and if they try to enter a number a pop up box will tell them they can only enter alpha characters. Can this be done? Here is my code:

How would you like us to address you? ("Dear Pat") Dear 
<input name="SALUT" type="text" id="address2" style="color: #000000; border-left: 0px solid #008000; border-right: 0px solid #254D78; border-top: 0px solid #008000; border-bottom: 2px solid #0033CC; background-color: #EBE1BE" tabindex="5" size="15" maxlength="50" onFocus="if(this.value=='SALUT')this.value='';">

Any help would be greatly appreciated.

Thanks:confused:

shyam
Apr 9th, 2008, 05:37 PM
yes it is possible...you find out how if u spend some time searching the javascript forum

Philip M
Apr 9th, 2008, 05:59 PM
This should do the job:-



How would you like us to address you? (&quot;Dear Pat&quot) Dear&nbsp;
<input name="SALUT" type="text" id="address2" style="color: #000000; border-left: 0px solid #008000; border-right: 0px solid #254D78; border-top: 0px solid #008000; border-bottom: 2px solid #0033CC; background-color: #EBE1BE" tabindex="5" size="15" maxlength="50" onFocus="if(this.value=='SALUT')this.value='';" onblur = "checkField(this)">

<script type = "text/javascript">
function checkField(which) {
if (/[^a-z]/gi.test(which.value)) {
alert ("Only alpha characters are valid in this field"); // no spaces, full stops or anything but A-Z
which.value = "";
which.focus();
return false;
}
}
</script>

Suggest a small change here:-
onFocus="if(this.value.toLowerCase()=='salut') this.value= '' "; // trap salut regardless of case.


Quizmaster: Nelson's flagship HMS Victory was constructed mainly of which wood?
Contestant: Balsa.

Apr 9th, 2008, 08:19 PM
This is awsome. It works like a charm. Thank you so much for your help!
:D

Apr 9th, 2008, 09:03 PM
First, again thanks!

One question is it possible to be able to allow spaces?

If a person wants to be addressed as Dear: Tom and Charlotte or Tom & Charlotte

Can this be done? or at least the First Scenario Tom and Charlotte

:confused:

Philip M
Apr 9th, 2008, 09:41 PM
Change to:-


if (/[^a-z\s&]/gi.test(which.value)) {
alert ("Only alpha characters, spaces and & are valid in this field");

What about names such as Paddy O'Reilly, Dr. D'Eath and Tom Smith-Roberts?

You can cover these with:-


if (/[^a-z\s&'-\.]/gi.test(which.value)) {
alert ("Only alpha characters, spaces, apostrophe, hyphen, full stop and & are valid in this field");

Now that you have allowed spaces, you really need to strip leading spaces and check the field length to prevent just spaces being entered:-


<script type = "text/javascript">
function checkField(which) {
nm = which.value;
nm = nm.replace(/^\s+/,""); // strip leading spaces
if ((/[^a-z\s&'-\.]/gi.test(nm)) || (nm.length == 0)) {
alert ("Only alpha characters, space, apostrophe, hyphen, full stop and & are valid in this field");
which.value = "";
which.focus();
return false;
}
}
</script>

If you want you can refine this further to ensure that the field contains at least 2 alpha characters, thus weeding out ------, &&&&& and ....... (or similar silly entries)



<script type = "text/javascript">
function checkField(which) {
nm = which.value;
nm = nm.replace(/^\s+/,""); // strip leading spaces
nm1 = nm.replace(/[^a-z]/gi,""); // strip non-alpha chars
if ((/[^a-z\s&'-\.]/gi.test(nm)) || (nm.length == 0) || (nm1.length < 2)) {
alert ("Only alpha characters (2 minimum), space, apostrophe, hyphen, full stop and & are valid in this field");
which.value = "";
which.focus();
return false;
}
}
</script>

Apr 9th, 2008, 10:18 PM
That works great. Then I applied the following script in case a person doesn't use capitalization. That works but when the form is submitted the salutation only prints the first character as capital and leaves the rest lower case. Here is the script I used to make it capital and like I said it makes it capital looking at the form until it is submitted. What is your thoughts on this. I am new to all this so any help is appreciated. Thanks!

<SCRIPT LANGUAGE="JAVASCRIPT">
<!--

function capitalizeMe(obj) {
val = obj.value;
newVal = '';
val = val.split(' ');
for(var c=0; c < val.length; c++) {
newVal += val[c].substring(0,1).toUpperCase() +
val[c].substring(1,val[c].length) + ' ';
}
obj.value = newVal;
}

// -->
</SCRIPT>

<FORM NAME="TEST">
<INPUT TYPE="TEXT" NAME="TESTER" onChange="capitalizeMe(this)">
</FORM>

Apr 10th, 2008, 03:02 PM
Still having problems with the Capitalization script. It works while in the form but as soon as you submit it loses the capitalization.

Another problem is I am using this script to make sure they check at least one petition: Now that I have your script in it no longer pops up a box to tell you to select a petition. Any thoughts on this? Can you use more than one check function in a page? The page I am using these scripts in is:

https://www.amm.org/bulletins/2008/may/petitions.asp

<script type="text/javascript">
<!--
function check (f) {
var e, i = 0, checked = false;
while (e = f.elements[i++]) {if (e.type == 'checkbox' && e.checked) checked = true};
if (!checked) alert ('Please select your petition(s)');
return checked;
}
/
//-->
</script>


<form action="https://www.amm.org/submissions/scripts/EDUscript.asp" method="post" name="form" id="form" onsubmit="return check (this)">

Any help is much appreciated! :(

Philip M
Apr 10th, 2008, 04:34 PM
That works great. Then I applied the following script in case a person doesn't use capitalization. That works but when the form is submitted the salutation only prints the first character as capital and leaves the rest lower case.

I am not sure what it is exactly that you are trying to achieve.

If you want to return the entered text in lower case but with an initial capital (Philip) then:

newVal = obj.value.toLowerCase();
newVal = newVal.substring(0,1).toUpperCase() + newVal.substring(1,newVal.length);

If you want to make it all uppercase (PHILIP) then simply:-

newVal = obj.value.toUpperCase();

Apr 10th, 2008, 04:47 PM
The script I am using is supposed to capital the first letter of each word. Which it does when you look at the form. For example if a person types phillip and monica it converts it to Phillip And Monica. When the form is submitted it prints Phillip and monica and the auto email that is sent is addressed as Dear Philip and monica that's the problem. It doesn't hold onto the capitalization.

The other problem with the check fuction one is
onBlur = "checkField(this);" and the other is onsubmit="return check (this) is it not working because they both have (this) in the check?

I really appreciate the help!

Philip M
Apr 10th, 2008, 05:25 PM
The script I am using is supposed to capital the first letter of each word. Which it does when you look at the form. For example if a person types phillip and monica it converts it to Phillip And Monica. When the form is submitted it prints Phillip and monica and the auto email that is sent is addressed as Dear Philip and monica that's the problem. It doesn't hold onto the capitalization.



I can't account for this. It must be something in your PHP script. (EDIT) I take it that the validation is taking place before the form is submitted!




The other problem with the check function one is
onBlur = "checkField(this);" and the other is onsubmit="return check (this) is it not working because they both have (this) in the check?

I really appreciate the help!

No, this is a keyword which passes the id of the object to the function.

Remember that the .value of the object must be obtained:-

function checkfield(obj) {
someVariable = obj.value;

Apr 10th, 2008, 05:42 PM
Okay both the scripts are working now. Thanks!

The capitalization script is not or at least when it is submitted. Yes the validation is being done before the submit. And actually I can see it happen in front of me it is just not holding onto it when it submits. I just don't get it :(

Again thanks for your help!

Philip M
Apr 10th, 2008, 06:37 PM
The capitalization script is not or at least when it is submitted. Yes the validation is being done before the submit. And actually I can see it happen in front of me it is just not holding onto it when it submits. I just don't get it :(



function capitalizeMe(obj) {
val = obj.value;
alert (val) // philip and monica (who the **** is this Monica?. Not the Clinton Monica, surely?)
newVal = '';
val = val.split(' ');
for(var c=0; c < val.length; c++) {
newVal += val[c].substring(0,1).toUpperCase() +
val[c].substring(1,val[c].length) + ' ';
}
obj.value = newVal;
alert (document.TEST.TESTER.value); // Philip And Monica
}
As I say, I think the problem is on your server where the field is assumed to be a single word starting with a capital letter.

Apr 10th, 2008, 07:37 PM
You are probably right I will check the asp scripting on the submission form. I know I have built in IF and ELSEIF statements so maybe that is where I need to look. Again thanks for all your help. By the way those names just popped into my head no pun intended. HA HA!

Philip M
Apr 10th, 2008, 10:18 PM
if (/^Mc/.test(tmp))
{
tmp = tmp.replace(tmp.substring(2,3),tmp.substring(2,3).toUpperCase().replace(/ /g,""));
}
if (/^Mac/.test(tmp))
{
tmp = tmp.replace(tmp.substring(3,4),tmp.substring(3,4).toUpperCase().replace(/ /g,""));
}



FWIW, my understanding is that names starting with Mc have the third letter capitalised (McKay, McIntosh, McLelland), but names starting with Mac do not have the fourth letter capitalised (Macleod, Macdonald, Mack, Macaroni).

Philip M
Apr 11th, 2008, 09:19 AM
Okay, Philip M. Go ahead and correct the code, then.

Maybe you also want to have the code accept: philip & monica, philip and monica, in the first name field.

I'll defer to you. I'm finished.

No need to be shirty. :p I was simply pointing out that your code would turn Mack into MacK and Macaroni into MacAroni. Simply resolved by deleting that small block. Otherwise the code is fine and doubtless the OP is most grateful to you for posting it.

I don't want anything. The thread was raised by ammwebmaster2. As so often the OP changed the specification after having received the solution. For myself, I rather take the view that people who cannot manage to spell or capitalise their own names correctly get what they deserve.


For passing information only (I certainly did not know this before I Googled):-

"In the Scottish [yes: Scottish] Highlands, "Mac" indicating "son of" is very popular (MacDonald, MacWilliam), but if the letter following the "c" of the "Mac" is not capitalized, then the latter part of the name is not a Christian name but instead has an occupational derivation, eg, Macnab (son of the abbot), Macintyre (son of the carpenter) and Macpherson (son of the parson)."

hmpk
Apr 13th, 2011, 09:15 AM
I have read the reply given to this question and tried it on my form, however it didn't wotk for me.

I have just copied the part of my code where I want to add the alpha characters test.

It is working to validate if value is empty, but I must not be joining them together correctly.

I would like to also validate for ONLY characters, including ' . It doesn't matter about capitals.


function validateForm()
{



var x=document.forms["myForm"]["lastname"].value
if (x==null || x=="")
{
alert("Last name must be filled out");
return false;
}





<tr>
<td colspan="2" align=center>
<INPUT value="Submit" type="submit" onClick="return validateForm()">
<INPUT onclick="formreset()" value="Reset" type="reset"></TD>
</TR>
</TBODY>


IF ANYONE COULD HELP ME WITH THIS PLEASE I WOULD BE VERY GRATEFUL.

Philip M
Apr 13th, 2011, 09:30 AM
What was wrong with the code I posted in Post #6? If it does not work for you then "The fault, dear Brutus, lies not in the stars but ....."
Here you are, but you ought not to hijack someone else's ancient thread. Bumping up very old threads is highly frowned upon and requires ample justification for doing so. Prefer to start a new thread of your own. It would be a good idea to have a look at the forum rules and posting guidelines as well.





function validateForm() {
var x = document.forms["myForm"]["lastname"].value;
x = x.replace(/^\s+|\s+$/g,""); // strip all leading and trailing spaces
x = x.replace(/\s{2,}/g," "); // replace multiple spaces with one space
if (x.length < 2) {
alert("Last name must be filled out");
setTimeout('document.forms["myForm"]["lastname"].focus()', 25); // refocus on it
return false;
}
if (/[^a-z\s\-\']/gi.test (x)) { // only letters space hyphen apostophe allowed - Smith-Jones O'Flanaghan
alert ("You may only enter letters, space, hyphen, apostrophe");
document.forms["myForm"]["lastname"].value = ""; // clear the field
setTimeout('document.forms["myForm"]["lastname"].focus()', 25); // and refocus on it
return false;
}
x = x.toLowerCase().replace(/\b[a-z]/g,function(w){return w.toUpperCase()}); // format with capitals
document.forms["myForm"]["lastname"].value = x;
}



<INPUT value="Submit" type="submit" onClick="return validateForm()" >
The call to the validation routine should be in the <form> tag, so

<form name = "myForm" action = "" method = "post" onsubmit = "return validateForm()">



"In the beginner's mind there are many possibilities, but in the expert's mind there are few” - Shunryu Suzuki (Japanese Zen priest, ?-1971)

hmpk
Apr 14th, 2011, 12:20 AM
What was wrong with the code I posted in Post #6? If it does not work for you then "The fault, dear Brutus, lies not in the stars but ....."
Here you are, but you ought not to hijack someone else's ancient thread. Bumping up very old threads is highly frowned upon and requires ample justification for doing so. Prefer to start a new thread of your own. It would be a good idea to have a look at the forum rules and posting guidelines as well.





function validateForm() {
var x = document.forms["myForm"]["lastname"].value;
x = x.replace(/^\s+|\s+$/g,""); // strip all leading and trailing spaces
x = x.replace(/\s{2,}/g," "); // replace multiple spaces with one space
if (x.length < 2) {
alert("Last name must be filled out");
setTimeout('document.forms["myForm"]["lastname"].focus()', 25); // refocus on it
return false;
}
if (/[^a-z\s\-\']/gi.test (x)) { // only letters space hyphen apostophe allowed - Smith-Jones O'Flanaghan
alert ("You may only enter letters, space, hyphen, apostrophe");
document.forms["myForm"]["lastname"].value = ""; // clear the field
setTimeout('document.forms["myForm"]["lastname"].focus()', 25); // and refocus on it
return false;
}
x = x.toLowerCase().replace(/\b[a-z]/g,function(w){return w.toUpperCase()}); // format with capitals
document.forms["myForm"]["lastname"].value = x;
}



<INPUT value="Submit" type="submit" onClick="return validateForm()" >
The call to the validation routine should be in the <form> tag, so

<form name = "myForm" action = "" method = "post" onsubmit = "return validateForm()">



"In the beginner's mind there are many possibilities, but in the expert's mind there are few” - Shunryu Suzuki (Japanese Zen priest, ?-1971)
Thank you very much for your reply,I really appreciate your time helping me.

However, it still is not working.

Philip M
Apr 14th, 2011, 08:34 AM
Well, it works for me. :) Why does it not work? Error messages? Does nothing? Allows invalid entries? Blocks valid entries? Without more information it is impossible to assist you further. As I say, "The fault, dear Brutus, lies not in the stars ...."