Hi,
I'm working on form validation using javascript here. I'm given html files that contains forms to be validated, 5 of them (say pg1 - pg5) and they are written using php. My questions are;
1. The way to write javascript in .php files is the same as that in .html files, isn't it?
2. Suppose in pg1, I have an empty text box, then in pg4, I have two radio buttons (say "yes" and "no"). I need to validate such that if "yes" is checked, then the textbox must be filled in first before proceeding. How do i do that? My current idea is to have a hidden text box in pg4 that contains the value of the text box in pg1, but I don't know how to get this value.....please advice.
3. Using javascript, how do you automatically place cursor to a textbox when the page loaded?
Sorry to ask so many questions in my first post......Thanks
Dr. Script
January 27th, 2005, 06:41 PM
1. Yes, just realize that unlike the PHP, the JavaScript is evaluated by the client, not the server.
2. Not quite sure how the 5 pages will be related. Try to explain that a bit more.
3. Use the focus property:<script type="text/javascript">
1. So what does it mean by server side? does it mean that the values entered are checked against the database?When should we use javascript and when we need to use php?
2. Ok, pg1 - pg5 are related in a way that when you press submit button on pg1(after certain validation), save the data into database,then it will take you to another form on pg2 and so on until you reach pg5. So any idea?
3. So what's this function()? is that like a built in function? Where can I find infos about javascripts built in functions and/or methods?
4. This question is related to regular expression. If I want to validate a phone number that consist of "(" followed by two integer and ")" then followed by 8 integers, is this correct /^(\d{2})/d{8}$/ ?
Thanks Doc
Dia
January 28th, 2005, 03:44 AM
Hi,
Yeah, the way you write JS code in PHP files is the same. But you could also use PHP to execute JS code. For example, the following two statements in your .php file would have the same effect..... putting the cursor in a text box (with the name "id") in a form (whose name is "subscriptionForm") when the page loads!
Ideally, you should use PHP ONLY and ONLY when there is no way you can process further without the server-side related things like authentication from a databse at the server. All form checking (to the greatest possible extent) should be performed using JavaScript. That's a "Good Programming Practice" :)
You will have to transfer the value from the text box on pg1 onto pg4 using hidden fields at each intermediate page (in the forms that you use to call next page), no matter even if you have to create a separate form just for this field alone... else you will have to create temp files etc. and later delete them which is not that good an idea. Let's assume that the name of the field that you wanna transfer is "id". Now, in your 2nd page, this value is available as $id, right? So far so good? Then to transfer this field from page 2 to page 3, what you will do is that you will create following hidden field in your form of page 2:
<input name='hiddenID1' type='hidden' value='<? echo $id ?>'>
and your form will catch the value of field "id" and put it as the value for hiddenID1 through echo. And this value will be available to the script in page 3 as $hiddenID1. Simple! Isn't it? Lets move further.... Now similarly you will do this in form 3 to transfer value of hiddenID1 to hiddenID2 in form of page 4 where you check whether "Yes" is selected or not. If yes, then
if ($hiddenID2) {// means that initial ID field had *some* value in it --> No need for any corrective measure
} else { // Crucial step!
echo ("javascript:history.go(-3)"); // 'coz you need to go 3 pages back!
}
Hope it would help!
Take care & Allah Hafiz
~Dia
Dr. Script
January 28th, 2005, 04:31 PM
I agree with all Dia has posted except the form validation in regards to JavaScript. It is great to validate with JavaScript, but more than 1 in 10 users does not use it (81% at my site), so it lacks reliability. Every browser supporting forms supports PHP or other server side languages, so it is 100% reliable. 100 v. 81, hmm .
To follow up on number 3: function() simply declares an unnamed, anonymous function. When the page loads, the onload event is triggered, and runs the code within the function, which happens to focus to the text field.
For your 4th question:<script type="text/javascript">
// declare prototype to check if entry is valid format
String.prototype.isPhoneNum = function() {
// sends back whether or not phone number valid
return /^\s*\(\d{2}\)\s*\d{8}\s*$/.test(this);
}
do {
// get phone number from user
var rep = prompt("Please enter telephone number [(##)########]","");
// loop while the entry is not in valid format
} while(!rep.isPhoneNum());
// remove all whitespace from entry
rep = rep.replace(/\s/g,'');
</script>Dr. Script
pc_newbies
January 28th, 2005, 10:33 PM
Thanks Dia,
So to transfer the form contents I need to use php?
One thing that confused me, how do i get id in the first place? just set value = formname.textfieldname.value?
Thanks Doc, it makes sense to me.....
Thanks heaps guys, realy help me alot
pc_newbies
January 29th, 2005, 05:09 AM
3. Use the focus property:<script type="text/javascript">
I tried that but it doesn't work. Where should I put that code? outside <FORM> or <FORM ........ onLoad = "onload">?
Thanks
Dr. Script
January 29th, 2005, 07:24 AM
Place my code in the <head> section of the page. Then change formName to the name given to your form, and fieldName to the name of the text field. This code worked for me:<!-- doctype here -->
<html>
<head>
<title>Document</title>
<script type="text/javascript">
</style>
</head>
<body>
<!-- Body code here -->
<form name="formName" action="myScript.pl">
<fieldset><legend>Form: </legend>
<label>Text: <input type="text" name="fieldName"></label><br>
<div><button type="submit">Send >></button>
</fieldset>
</form>
<!-- Body code here -->
</body>
</html>
Dr. Script
pc_newbies
January 29th, 2005, 10:33 PM
Thanks Doc, it works. This is what I had before
<script type= "JavaScript">
function testing(){
document.form1.age.focus();
}
</script>
<FORM name = "form1" action = "POST" onload = "testing()"
Your age:<BR><INPUT TYPE="text" NAME="age" SIZE="2"><BR>
</FORM>
And it didn't work, so I got rid of
function testing(){
document.form1.age.focus();
}
and onload = testing()
Changed that to
onload = function{
document.form1.age.focus();
}
as you suggested and it works ok
Dr. Script
January 30th, 2005, 08:43 AM
Glad that you found success from the code. Were there any other questions you had a problem with? (Question 2 ... you may want to refer those to Dia)
Dia
January 30th, 2005, 11:37 AM
Assalam u Alaikum,
Yeah Doc, you are right about using PHP for form validation since not all of the users might have JS enabled. But then from good programming point of view, one should provide validation both in JS and PHP such that PHP validation must be invoked only if JS validation was not done (using some flag variables). That's duplication of effort at the programmer end (though not so much... considering that JS and PHP syntax is almost the same so you can always copy-paste and do slight modifications) but it definitely saves the browsing time of all the users who do have JS enabled browsers.
Turning to newbie's problem.... well, id is the name of your field on page 1 that you want to check if it is filled or not when "Yes" is clicked on page 4! You don't need to set the value of this id field at all. This would be filled in by the user at runtime and would be available to the PHP engine!
In order to capture fields from an HTML form, you need to use any of the server-side scripting language, whether it be PHP or ASP or anyother....
Take care & Allah Hafiz
~Dia
pc_newbies
January 31st, 2005, 04:46 AM
Thanks Doc, Thanks Dia.....helps me heaps.....
One more problem. With your phone number validation code, how do I get the value entered via rep (prompt windows) into the text box?
Dr. Script
January 31st, 2005, 03:56 PM
Do you want it to validate a form? If so, add to the <form> tag:onsubmit="return check(this);"Then replace evertything from the do { until the last semicolon (the replace line) and use:function check(f) {
// checks if field valid is valid, returns true (submits) if it is.
return f.phoneNum.value.isPhoneNum();
}Dr. Script
pc_newbies
January 31st, 2005, 11:19 PM
Thanks Doc for that
Sorry to bother you again, suppose I'm validating a text field or radio button or any other forms, and if the value is missing or invalid, I want to highlight that specific field(change the colour of the field maybe), the validatation routine occur everytime user fills in each field and also when the user click submit button. How do I do that using javascript? Or if you have any other suggestion? All I want to do is to let the user know where the invalid field is.
Also, I tried to put an input mask for phone number. I got the following code
<fieldset class="fld" style="height:100px;"><legend>Errors</legend>
<div id="errors" style="color:red;font-weight:bold;">
Any errors will be posted here.
</div>
</fieldset>
</body>
</html>If the set attribute is "required," it validates if the values meets the regular expression. That should work nicely for you. If you want to validate just to make sure something is entered (any character), you can use the RegExp: /^.{#}$/ (where # is the minimum length).
Also, be sure to give your field ids. The id field displays in the error box. Also if you change the name of the form, do so in the variable at the top. It is possible to incorporate more forms, however, it will need some minor adjustments.
Dr. Script
pc_newbies
February 1st, 2005, 11:24 PM
G'day Doc,
Great code.....thanks doc. I use a slightly diffrent thing. I use <span> </span> to write the error messages and I use getElementById(id) to set the border color of the text box or whatever when an error occur print out the message.
Coz in my validation routine, I need to validate each field as the user entering info and check it first before goes to the next field (with out submitting the field). Then when the user click submit, once again the validation routine is called and this time validates the whole form(fields). All I'm wondering now, how do I clear the error message written in "<span>" area after each field validation(coz it doesn't load the page when the user move from one field to another)?
Thanks doc
Dr. Script
February 2nd, 2005, 06:47 AM
What is the code you are using?
Dr. Script
pc_newbies
February 2nd, 2005, 09:35 PM
Attached is the code that i'm using.
Don't worry about it Doc, problem solved.
To clear message, I just write an empty string to span. And since getElementById(varId).style.bordercolor can't be used with dropdown menu (select menu), I put id inside <td> since I'm using table, then just change the font color instead of the border color
No more problem so far....I'll post it as soon as I get one
Thanks heaps Doc
pc_newbies
February 4th, 2005, 02:14 AM
Hi Doc,
I got another problem here. Remember that I use getElementById(varID).style.bordercolor to change the border color of the text box? How do I set it back to the default text box?
Thanks
Dr. Script
February 4th, 2005, 06:47 AM
You can set the className (just like value) to the class with the standard attributes. I'll try to develop something soon.
Dr. Script
Dr. Script
February 4th, 2005, 03:35 PM
Didn't even see your "don't worry about it" message. Umm ... can't you just set the bordercolor back to whatever it starts at? If getting that is the problem, just alert the bordercolor before changing it so you get the default color.
pc_newbies
February 4th, 2005, 10:20 PM
When I created the text box, i didn't set the border value, and I did try the alert box and it returned unknown. I'll give it a try one more time and I'll post the result here.
Do you know how to put an input mask? for phone number? There's one thread in this forum, and I also found a script from the web
and it returns an error, I think the error says object error or something(something to do with "this").
Thanks
Dr. Script
February 5th, 2005, 08:44 AM
Do you have the .js file for the dFilter function?
If I were you, I'd create them all a class with border-color: black; Then simply make it red (bad input) or black (good input).
Dr. Script
pc_newbies
February 6th, 2005, 12:24 AM
Right, my mistake, didn't see the .js file is required. Do you have any js for phone input mask, the simple one? The code that i got from the web is like 20 lines long and rather complicated.
Thanks Doc
Dr. Script
February 6th, 2005, 08:40 AM
I dont have one no ... and it might be better to use that one (since it works ;)). However, if would like an explanation of the code, go ahead and post it.
pc_newbies
February 7th, 2005, 12:46 AM
Thanks Doc for your offer,
Back to my problem; getting field value from other form on other page. As Dia suggested;
You will have to transfer the value from the text box on pg1 onto pg4 using hidden fields at each intermediate page (in the forms that you use to call next page), no matter even if you have to create a separate form just for this field alone... else you will have to create temp files etc. and later delete them which is not that good an idea. Let's assume that the name of the field that you wanna transfer is "id". Now, in your 2nd page, this value is available as $id, right? So far so good? Then to transfer this field from page 2 to page 3, what you will do is that you will create following hidden field in your form of page 2:
<input name='hiddenID1' type='hidden' value='<? echo $id ?>'>
and your form will catch the value of field "id" and put it as the value for hiddenID1 through echo. And this value will be available to the script in page 3 as $hiddenID1. Simple! Isn't it?
And I did that,
I have
<input type="hidden" name="agediff2" id ="agecheck2" value='<? echo $agediff ?>'>
on the page(pg2) where value from the first page(pg1) is needed, and I have
<input type="hidden" name="agediff" id ="agecheck" value= age>
on my first page where age is just a variable as a result of a function called ageDifference() which calculates the person's age.
and when I load on the pg2, and print the value, I got "echo $agediff "
All I'm trying to do here is to set the value of the hidden textbox on pg2 to the value of hidden textbox on pg1 using echo $agediff(as Dia suggested) then access this with java script using document.getElementById("agecheck2").value. So, any idea Doc?
Thanks
pc_newbies
February 8th, 2005, 03:10 AM
It's all done now. All I did is to put a hidden field on pg2 with the value of the text field value on pg1. I stored the value of pg1 on index.php
So on pg2 I have <input type="hidden" id="gd" value="{GENDER_ID}">
One more problem, I have two select boxes, s1 and s2
Suppose if s1[1] is selected then user can't select s2 (disabled) How do I do that?
Thanks
Dr. Script
February 8th, 2005, 06:43 AM
You'd use the select tags, onselect option. If the selectedIndex is 1, set the disabled property of s2 to the boolean true, or otherwise, false. If you can't get it working, I'll have time later.
<select id="s2">
<option>0b</option>
<option>1b</option>
<option>2b</option>
<option>3b</option>
<option>4b</option>
</select>That works in IE ... but Mozilla will always disable it, disregardless whether or not the selectedIndex is 1 or not. The reason, the attribute in Mozilla iis always true while it exists. In IE, the false boolean makes the attrbiute false. All other values make it true.
If anyone can modify for Mozilla, surely do so.
Dr. Script
pc_newbies
February 8th, 2005, 11:37 PM
It works like a charm Doc, thanks. One question though; suppose s2[3] has been selected, then the user change the value of s1 to "1" (i.e s1.selected == "1"), then s2 is disabled however,would s2[3] be stored when the form is submitted?
I want the value of s2 is set back to s2[0] when it is disabled/
Thanks
Dr. Script
February 9th, 2005, 06:41 AM
When submitting a form, all disabled form elements are not submitted. That shouldn't be a problem.
pc_newbies
February 10th, 2005, 02:12 AM
Thanks for the tip doc. As I promised you about the code for the input mask. I'm using dFilter that I got from http://javascript.internet.com/forms/dfilter.html
// [dFilter] - A Numerical Input Mask for JavaScript
// Written By Dwayne Forehand - March 27th, 2003
// Please reuse & redistribute while keeping this notice.
function dFilterMax (dFilterMask)
{
dFilterTemp = dFilterMask;
for (dFilterStep = 0; dFilterStep < (dFilterMask.length+1); dFilterStep++)
{
if (dFilterMask.charAt(dFilterStep)!='#')
{
dFilterTemp = replace(dFilterTemp,dFilterMask.charAt(dFilterStep),'');
}
}
return dFilterTemp.length;
}
function dFilter (key, textbox, dFilterMask)
{
dFilterNum = dFilterStrip(textbox.value, dFilterMask);
if (key==9)
{
return true;
}
else if (key==8&&dFilterNum.length!=0)
{
dFilterNum = dFilterNum.substring(0,dFilterNum.length-1);
}
else if ( ((key>47&&key<58)||(key>95&&key<106)) && dFilterNum.length<dFilterMax(dFilterMask) )
{
dFilterNum=dFilterNum+String.fromCharCode(key);
}
var dFilterFinal='';
for (dFilterStep = 0; dFilterStep < dFilterMask.length; dFilterStep++)
{
if (dFilterMask.charAt(dFilterStep)=='#')
{
if (dFilterNum.length!=0)
{
dFilterFinal = dFilterFinal + dFilterNum.charAt(0);
dFilterNum = dFilterNum.substring(1,dFilterNum.length);
}
else
{
dFilterFinal = dFilterFinal + "";
}
}
else if (dFilterMask.charAt(dFilterStep)!='#')
{
dFilterFinal = dFilterFinal + dFilterMask.charAt(dFilterStep);
}
// dFilterTemp = replace(dFilterTemp,dFilterMask.substring(dFilterStep,dFilterStep+1),'');
}
textbox.value = dFilterFinal;
return false;
}
function replace(fullString,text,by) {
// Replaces text with by in string
var strLength = fullString.length, txtLength = text.length;
if ((strLength == 0) || (txtLength == 0)) return fullString;
var i = fullString.indexOf(text);
if ((!i) && (text != fullString.substring(0,txtLength))) return fullString;
if (i == -1) return fullString;
var newstr = fullString.substring(0,i) + by;
if (i+txtLength < strLength)
newstr += replace(fullString.substring(i+txtLength,strLength),text,by);
return newstr;
}
I got it working on my phone number field. However since phone number is not necessary, it can be blank. If user has inputted the phone number and then change his mind and wants it blank instead,and press "backspace" key. But Can't get rid of "()" (phone format is (##) #### ####). How do I clear this field?
My code before is
if(form.phone.value == "()") form.phone.value=""
And obviously It doesn't work
Dr. Script
February 10th, 2005, 06:44 AM
In the textbox, the onkeyup event, add that if block:<input ... onkeyup="if(this.value=='()') this.value='';" ... >
That code looks really sloppy and long. No wonder why it confuses people (such as you). I might justhave a look at it and improve upon it for you ...
Dr. Script
pc_newbies
February 10th, 2005, 09:45 PM
I agree Doc, the code is a bit confusing. Btw, i put the onkeyup and it still doesn't want to get rid of "()". This is what I have
<tr align="left" valign="top">
<td valign="middle" id = "ph" nowrap>Telephone</td>
<td><input type="text" style="width:100%" class="TaskEdit_tf" name="phone1" id= "ph1" value="{PHONE1}" onkeyup= "if(this.value=='()')this.value=' ';" onkeydown="javascript:return filter(event.keyCode,this,'(##) #### ####');"></td>
</tr>
Dr. Script
February 11th, 2005, 03:00 PM
It works for me. The error might be a result of the dFilter function. If that causes an error, it won't work, since the onkeydown event triggers before the onkeyup event handler.
pc_newbies
February 13th, 2005, 09:42 PM
I tried onblur and onload,but still doesn't work. Then I do a little experiment using the following code;
It always prints "()" and doesn't change the value. Seems that the dFilter() always set the value back to "()" no matter what I do.
Then I tried to use onkeypress=dfilter(blablabla)......and it works
Thanks Doc for the tip, I think my works nearly done. Been a great help Doc, thanks. Hope this thread can also help others
codeguru.com
Copyright Internet.com Inc., All Rights Reserved.