I want to use javascript with php for validation of fields on the form. But if validate returns false it should display message regarding the particular field and if it returns true then form should be submitted with the desired info otherwise the form should be submitted.... My partial code is as:

<?php 
session_start();
if(!$_SESSION['sessionusername'])
{
	header("location:index.php");
}
else
{
	include ('connection2.php');
	$local_session = $_SESSION['sessionusername'];




}


?>


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="stylesheet" media="screen" href="css/master.css">
<link rel="stylesheet" media="screen" href="css/menus.css">

<title>Phytec India</title>
<script type="text/javascript">
function validate()
{
	//******* I want my validation code should be here***************//
}



</script>

</head>
<form id="ndep" name="ndep" method="POST"  action=<?php 
	if(isset($_POST['s_close']))
	{
		header("location:department.php");	
	}
	elseif(isset($_POST["btn_save"]))
	{	
		"newdepartment.php";

}
?>
<div id="text_controls">
	              <?php /*?><input type="text" maxlength="6" name="text_depid" value="<?php if(count($errors)) echo isset($_POST['text_depid']) ? $_POST['text_depid'] : "" ?>"  width="auto" style="height:15px;"/><?php */?>
                 <input type="text" maxlength="30" name="text_depid"  width="auto" style="height:15px;"
                  value="<?php if (isset($_POST["save_btn"]))
				  						echo $deptname;
									?>"/> 

                 <span class="error"><?php  echo $depidErr;?></span> 
            </div>
<div id="text_controls">
                	<input type="text" maxlength="30" name="text_depname"  width="auto" style="height:15px;" 
                    value="<?php if (isset($_POST["save_btn"]))
							echo $deptname;
							?>"/>

                 <span class="error"><?php  echo $depidErr;?></span>
            </div>
<div id="nav_btn">
          <input type="submit" name="btn_save" value="Save" onclick="return validate()" />

            <input type="submit" name="s_close" value="Close" />
            </div>

Please help me to solve the problem......

    function validate() {
    	//******* I want my validation code should be here***************//
    }
    
    </script>

    I'm going to attempt to persuade you, for your own good, to actually study Javascript and join a Javascript user group or forum. Tell your employer it's important and may take a couple weeks.

    Get a book about Javascript and read it. Go to Youtube and look for "Douglas Crockford Javascript" videos. Join a Javascript forum. Incidentally, I have to chuckle, not at you per se, but at the fact that so many of us have just assumed we can write Javascript without bothering to take any time to learn about the language first ... an observation Doug Crockford made long ago and has popularized at every opportunity. I've been programming for over a decade (first for myself as a consultant, and now for 3 years for a business in a nearby city) and that's exactly how I approached JS until recently.

    I'll recommend that whatever JS you come up with, you run it through JSLint (JSLint.com) and make sure it's up to spec. Note that in the example above I've corrected your bracket style; it's not critical in PHP but in JS it can bite your behind, so put the bracket on the right after the statement to be evaluated:

    if (foo) {
       ...
    }

    The basic idea for your script is this: each element that you want verified should have an ID in the DOM (or some other handle, but ID works best for most elements). Your script will then create a variable that represents each node/element, test the value that is attached to it, and provide feedback to the user if it doesn't match your criteria. Here's a partial example of some recent work I did in this area:

    formCheck = function() {
       'use strict'; 
       var today,error,errorstr,terms,fname,lname,email,company,cats,checkedCats,title,titleChecked,address,city,state,zip,country,selectedCard,thisyear,thismonth,useCard,usePaypal,
          cvv,cardName,selYear,selMonth,phoneCountry,phoneArea,phoneNumber,catlen,i,element;
    
       error = 0;checkedCats = 0;titleChecked = 0;
    
       //phone number is required, but not extension
       phoneCountry = document.getElementById("phone_country").value;
       phoneArea = document.getElementById("phone_area").value;
       phoneNumber = document.getElementById("phone_num").value;
       phoneNumber = phoneNumber.replace("-",'');
    
       if (phoneCountry==='1' && phoneArea <100) { //North America, but no area code
          error++;
          errorstr="Please provide the area code with your phone number.";
       }
       if (!phoneCountry) {
          error++;
          errorstr="Please provide the country code with your phone number.";
       }
       if (phoneNumber.length < 4) {
          error++;
          errorstr="Please enter/check your phone number.";
       }
    
       //Address is required, ditto city, state, zip, country.
       country = document.getElementById("country").value;
       if (MYJS.minString(country,2) === 0 || country===" --Select One-- ") {
          error++;errorstr = "Please select your country.\n";
       }   
    zip = document.getElementById("zip").value; if (MYJS.minString(zip,5) === 0) { error++;errorstr = "You must enter your postal code/ZIP code.\n"; }
    state = document.getElementById("state").value; if (MYJS.minString(state,5) === 0) { error++;errorstr = "You must enter your state/province.\n"; }
    city = document.getElementById("city").value; if (MYJS.minString(city,4) === 0) { error++;errorstr = "You must enter your city.\n"; }
    address = document.getElementById("address").value; if (MYJS.minString(address,5) === 0 || address.indexOf(" ")<0) { error++;errorstr = "You must enter your street address.\n"; } //First and last name are required; (reversed here intentionally). lname = document.getElementById("last_name").value; if (MYJS.minString(lname,3) === 0) { error++;errorstr = "You must enter your last (family) name.\n"; } fname = document.getElementById("first_name").value; if (MYJS.minString(fname,3) === 0) { error++;errorstr = "You must enter your first (given) name.\n"; } //title "Mr. Mrs., etc." is required... title = document.getElementById("title_mr"); if (title.checked) { titleChecked++; } title = document.getElementById("title_mrs"); if (title.checked) { titleChecked++; } title = document.getElementById("title_ms"); if (title.checked) { titleChecked++; } if (!titleChecked) { error++;errorstr = "Please indicate 'Mr.', 'Ms.', or 'Mrs.'\n"; } // AND SO ON ...

    Now, in this example, I'm not sure why I have a "minString" function in the MYJS, but I do, so I used it.

    Your JS is highly tied to the DOM for the page it appears on, so it's pretty difficult to ask a bunch of folks without access to the completed project to do much helping except on answering specific questions ("what goes here" isn't one of them, I think). It might be a good idea to learn JQuery, Prototype, or Mootools, or some other JS library, to handle the DOM for you ("it's the worst API ever" --- Crockford again), even.

    You do need to decide how you'll present the error message; in olden days, "document.alert(msg)" was often used but it's no longer recommended; this means you need to learn to create a "modal window" ...

    As I said at first, a JS forum would be the place to ask, and then only after you've given time to learn how to use Javascript.

      Also note that all validation you do in Javascript should be duplicated in PHP code, since Javascript is a client-side language and can be altered or even disabled altogether.

      EDIT: Also, thread moved to ClientSide Technologies forum since this appears to be more of a Javascript question than a PHP one. Note that it's not possible to use Javascript "with" PHP since the two languages are on completely opposite ends of the spectrum (one is a client-side language, one is a server-side one).

        @

        Since, Javascript is client side language thats why i want the validation should be done at client rather then sending request to the server by adopting the server scripting (PHP). In this way i can utilize the much time....

          Yes, I understand that. However, you must duplicate all of that validation in the server-side code rather than rely on it being done by the client, since...

          bradgrafelman;11035351 wrote:

          Javascript is a client-side language and can be altered or even disabled altogether.

            But the thing is that why i have to duplicate the validation in the server-side code. If you don'd mind then would you please elaborate your thoughts so that i can understand your concept

              I can't really get any more elaborate than the text I've already quoted. Any and all Javascript can be modified or completely bypassed, so you can't rely on it as your only means of validation. Yes, it's very convenient since it can be used to provide immediate feedback to the user that something is wrong. No, you can't rely on the user not tampering or bypassing with it.

                You can't trust anything that comes from the browser: you don't control it. It might not even be a browser. It might be a script someone wrote making the request, and your page and the JavaScript it contains would never have been involved at all.

                  6 days later
                  Weedpacket;11035371 wrote:

                  You can't trust anything that comes from the browser: you don't control it. It might not even be a browser. It might be a script someone wrote making the request, and your page and the JavaScript it contains would never have been involved at all.

                  I strongly agree with you. Serious control is very important in such a case.

                    Write a Reply...