title: Javascript validation with php sample 1
body: <p>I have a form with 4 fields
  First Name (required)
  Last Name (required)
  Email (required)
  phone (optional) (if user enter any it should validate to a number or not) below is the form i have </p>
  
  <pre><code>&lt;form name="myForm" method="post" onsubmit="return validate();"&gt;
  First Name : &lt;input type="text" name="fname" id="id_fname"&gt; &lt;br&gt;
  Last Name : &lt;input type="text" name="lname" id="id_lname"&gt; &lt;br&gt;
  Email : &lt;input type="text" name="email" id="id_email"&gt; &lt;br&gt;
  Phone : &lt;input type="text" name="phone" id="id_phone"&gt; &lt;br&gt;
  &lt;input type="submit" value="send"&gt;
  &lt;/form&gt;
  </code></pre>
  
  <p>And below is the javascript code</p>
  
  <pre><code>&lt;script type="text/javascript"&gt;
  function validate()
  {
   if (document.myForm.id_fname.value == '') {
  alert("Enter First Name"); 
  return false;}
  
  else if(document.myForm.id_lname.value == '') {
  alert("Enter Last Name");
  return false; }
  </code></pre>
  
  <p>// now here email validation is not working</p>
  
  <pre><code>else if(document.myForm.id_email.value == '' || document.myForm.id_email.value != ''){
  var x = document.myForm.id_email.value;
      var atpos=x.indexOf("@");
      var dotpos=x.lastIndexOf(".");
      if (atpos&lt;1 || dotpos&lt;atpos+2 || dotpos+2&gt;=x.length)
      alert("Not a valid e-mail address");
      return false;
      else
      return true;
      } 
  </code></pre>
  
  <p>// this is for phone number, if this field is empty no validation, if this field not empty it should validate to contain only numbers</p>
  
  <pre><code>else if(document.myForm.id_phone != '') {
  var ValidChars = "0123456789";
  var IsNumber=true;
  var Char;
  sText = document.form1.testfield2_phone.value ;
  for (i = 0; i &lt; sText.length &amp;&amp; IsNumber == true; i++)
  {
  Char = sText.charAt(i);
  if (ValidChars.indexOf(Char) == -1)
  {
  IsNumber = false;
  }
  }
  
  if(IsNumber == false)
  alert("Enter valid Number");
  return false;
  else
  return true;
  }
  
  
  else
  return true;
  document.myForm.submit();
  }
  &lt;/script&gt;
  </code></pre>
  
  <p>Email validation and phone validation are not working when i comment these email and phone i get validation good for first name and last name... is there any error in code for validation.</p>
  
  <p>And when a form is submitted, when we refresh then details are resubmitted again, how to avoid this.</p>