473,513 Members | 3,621 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

URGENT: form validation

274 Contributor
I am trying form valdiation with javascript but it never call the function. can someone please test this code and see why it is like that. It screwed up my mind.
here is my code:
Expand|Select|Wrap|Line Numbers
  1. <!-- Java Script form form validation and entries -->
  2. <script language="JavaScript">
  3. function checkForm()
  4. {
  5. alert("I am called");
  6.    var cfirstname, cemail, cpass, clastname;
  7.  
  8.    with(window.document.msgform)
  9.    {
  10.       cfirstname    = firstname;
  11.       cemail   = email;
  12.       cpass = pass;
  13.       clastname = lastname;
  14.    }
  15.  
  16.    if(trim(cfirstname.value) == '')
  17.    {
  18.       alert('Please enter your first name');
  19.       cfirstname.focus();
  20.       return false;
  21.    }
  22.    else if(trim(cemail.value) == '')
  23.    {
  24.       alert('Please enter your email');
  25.       cemail.focus();
  26.       return false;
  27.    }
  28.    else if(!isEmail(trim(cemail.value))) // validate email address
  29.    {
  30.       alert('Email address is not valid');
  31.       cemail.focus();
  32.       return false;
  33.    }
  34.    else if(trim(cpass.value) == '')
  35.    {
  36.       alert('Please enter your password');
  37.       cpass.focus();
  38.       return false;
  39.    }
  40.    else if(trim(clastname.value) == '')
  41.    {
  42.       alert('Please enter your lastname');
  43.       clastname.focus();
  44.       return false;
  45.    }
  46.    else
  47.    {
  48.       cfirstname.value    = trim(cfirstname.value);
  49.       cemail.value   = trim(cemail.value);
  50.       cpass.value = trim(cpass.value);
  51.       clastname.value = trim(clastname.value);
  52.       return true;
  53.    }
  54. }
  55.  
  56. function trim(str)
  57. {
  58.    return str.replace(/^\s+|\s+$/g,'');
  59. }
  60.  
  61. function isEmail(str)
  62. {
  63.    var regex = /^[-_.a-z0-9]+@(([-_a-z0-9]+\.)+(ad|ae|aero|af|ag|
  64. ai|al|am|an|ao|aq|ar|arpa|as|at|au|aw|az|ba|bb|bd|be|bf|bg|
  65. bh|bi|biz|bj|bm|bn|bo|br|bs|bt|bv|bw|by|bz|ca|cc|cd|cf|cg|
  66. ch|ci|ck|cl|cm|cn|co|com|coop|cr|cs|cu|cv|cx|cy|cz|de|dj|dk|
  67. dm|do|dz|ec|edu|ee|eg|eh|er|es|et|eu|fi|fj|fk|fm|fo|fr|ga|gb|
  68. gd|ge|gf|gh|gi|gl|gm|gn|gov|gp|gq|gr|gs|gt|gu|gw|gy|hk|hm|hn|
  69. hr|ht|hu|id|ie|il|in|info|int|io|iq|ir|is|it|jm|jo|jp|ke|kg|
  70. kh|ki|km|kn|kp|kr|kw|ky|kz|la|lb|lc|li|lk|lr|ls|lt|lu|lv|ly|
  71. ma|mc|md|mg|mh|mil|mk|ml|mm|mn|mo|mp|mq|mr|ms|mt|mu|museum|
  72. mv|mw|mx|my|mz|na|name|nc|ne|net|nf|ng|ni|nl|no|np|nr|nt|nu|
  73. nz|om|org|pa|pe|pf|pg|ph|pk|pl|pm|pn|pr|pro|ps|pt|pw|py|qa|
  74. re|ro|ru|rw|sa|sb|sc|sd|se|sg|sh|si|sj|sk|sl|sm|sn|so|sr|st|
  75. su|sv|sy|sz|tc|td|tf|tg|th|tj|tk|tm|tn|to|tp|tr|tt|tv|tw|tz|
  76. ua|ug|uk|um|us|uy|uz|va|vc|ve|vg|vi|vn|vu|wf|ws|ye|yt|yu|za|
  77. zm|zw)|(([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5])\.){3}([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5]))$/i;
  78.  
  79. return regex.test(str);
  80. }
  81. </script>
  82.  
  83.  
  84. <?php 
  85. // Connects to your Database 
  86. include_once ('connection.php');
  87. include_once ('class.countries.inc.php');
  88. //This code runs if the form has been submitted
  89. if (isset($_POST['submit'])) { 
  90. echo("going to check");
  91. echo "<SCRIPT LANGUAGE='javascript'>checkForm();</SCRIPT>";
  92. //This makes sure they did not leave any fields blank
  93. if (!$_POST['firstname'] |!$_POST['lastname'] |!$_POST['email'] | !$_POST['pass'] | !$_POST['pass2'] | !$_POST['company'] | !$_POST['address1']| !$_POST['city']| !$_POST['province']
  94.     | !$_POST['country']| !$_POST['postalcode']| !$_POST['phone']| !$_POST['sub1']| !$_POST['sub2']
  95.     ) {
  96. die('You did not complete all of the required fields');
  97. }
  98. // checks if the username is in use
  99. if (!get_magic_quotes_gpc()) {
  100.     $_POST['email'] = addslashes($_POST['email']);
  101. }
  102.     $usercheck = $_POST['email'];
  103.     $check = mysql_query("SELECT email FROM member WHERE email = '$usercheck'") 
  104.     or die(mysql_error());
  105.     $check2 = mysql_num_rows($check);
  106. //check if the name exists it gives an error
  107. if ($check2 != 0) {
  108.     die('Sorry, the email '.$_POST['email'].' is already in use.');
  109. }
  110. //  makes sure both passwords entered match
  111. if ($_POST['pass'] != $_POST['pass2']) {
  112.     die('Your passwords did not match. ');
  113. }
  114. // encrypt the password and add slashes if needed
  115.     $_POST['pass'] = md5($_POST['pass']);
  116. // check for addslashes    
  117. if (!get_magic_quotes_gpc()) {
  118.     $_POST['firstname'] = addslashes($_POST['firstname']);
  119.     $_POST['lastname'] = addslashes($_POST['lastname']);
  120.     $_POST['pass'] = addslashes($_POST['pass']);
  121.     $_POST['email'] = addslashes($_POST['email']);
  122.     $_POST['company'] = addslashes($_POST['company']);
  123.     $_POST['address1'] = addslashes($_POST['address1']);
  124.     $_POST['city'] = addslashes($_POST['city']);
  125.     $_POST['province'] = addslashes($_POST['province']);
  126.     $_POST['country'] = addslashes($_POST['country']);
  127.     $_POST['postalcode'] = addslashes($_POST['postalcode']);
  128.     $_POST['phone'] = addslashes($_POST['phone']);
  129.     $_POST['sub1'] = addslashes($_POST['sub1']);
  130.     $_POST['sub2'] = addslashes($_POST['sub2']);
  131. }
  132.  
  133. //  insert it into the database
  134. /*     $insert = "INSERT INTO member (firstname,lastname,company,region,title,address1,address2,city,province,country,postalcode,
  135.                 phone,fax,email,password,website,noofsubscriber,noofaddressablesubscriber)
  136.         VALUES ('".$_POST['firstname']."', '".$_POST['lastname']."', '".$_POST['company']."', '".$_POST['region']."',
  137.                 '".$_POST['title']."', '".$_POST['address1']."', '".$_POST['address2']."', '".$_POST['city']."', '".$_POST['province']."',
  138.                 '".$_POST['country']."',' ".$_POST['postalcode']."', '".$_POST['phone']."', '".$_POST['fax']."', '".$_POST['email']."', '".$_POST['pass']."',
  139.                 '".$_POST['website']."', '".$_POST['sub1']."', '".$_POST['sub2']."')";
  140.         $add_member = mysql_query($insert); */
  141.         $insert = "INSERT INTO member (firstname,lastname,company,region,title,
  142.                    address1,address2,city,province,country,postalcode,
  143.                    phone,ext,fax,email,password,website,noofsubscriber,noofaddressablesubscriber)
  144.         VALUES ('".$_POST['firstname']."', '".$_POST['lastname']."', '".$_POST['company']."', '".$_POST['region']."', '".$_POST['title']."',
  145.                 '".$_POST['address1']."', '".$_POST['address2']."', '".$_POST['city']."', '".$_POST['province']."', '".$_POST['country']."', '".$_POST['postalcode']."',
  146.                 '".$_POST['phone']."', '".$_POST['ext']."', '".$_POST['fax']."', '".$_POST['email']."', '".$_POST['pass']."',
  147.                 '".$_POST['website']."', '".$_POST['sub1']."', '".$_POST['sub2']."')";
  148.         $add_member = mysql_query($insert);
  149. ?>
  150. <h1>Registered</h1>
  151. <p>Thank you, you have registered - you may now login</a>.</p>
  152. <?php 
  153. else 
  154. ?>
  155. <!-- action="<php echo $_SERVER['PHP_SELF']; ?>" -->
  156. <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" name="msgform" >
  157. <table border="0">
  158. <tr><td>First Name:</td><td>
  159. <input type="text" name="firstname" maxlength="50" size=50>
  160. </td></tr>
  161. <tr><td>Last Name:</td><td>
  162. <input type="text" name="lastname" maxlength="50" size=50>
  163. </td></tr>
  164. <tr><td>Company:</td><td>
  165. <input type="text" name="company" maxlength="150" size=60>
  166. </td></tr>
  167. <tr><td>Divion/Region:</td><td>
  168. <input type="text" name="region" maxlength="50" size=50>
  169. </td></tr>
  170. <tr><td>Title:</td><td>
  171. <input type="text" name="title" maxlength="50" size=50>
  172. </td></tr>
  173. <tr><td>Address 1:</td><td>
  174. <input type="text" name="address1" maxlength="150" size=60>
  175. </td></tr>
  176. <tr><td>Address 2:</td><td>
  177. <input type="text" name="address2" maxlength="150" size=60>
  178. </td></tr>
  179. <tr><td>City:</td><td>
  180. <input type="text" name="city" maxlength="50" size=50>
  181. </td></tr>
  182. <tr><td>State/Province:</td><td>
  183. <input type="text" name="province" maxlength="50" size=50>
  184. </td></tr>
  185. <tr><td>Country:</td><td>
  186. <!-- <input type="text" name="country" maxlength="50"> -->
  187. <?php
  188. $countryObj = new countries;
  189.       $countryselect = $countryObj->countrySelect(
  190.          array('name'=>'country',
  191.               'style'=>'width: 200px; color: blue;'
  192.       ),$country?$country:"ca");
  193.  
  194.    echo $countryselect;
  195.   ?>
  196. </td></tr>
  197. <tr><td>Zip/Postal Code:</td><td>
  198. <input type="text" name="postalcode" maxlength="6" size=50>
  199. </td></tr>
  200. <tr><td>Phone:</td><td>
  201. <input type="text" name="phone" maxlength="15"> Ext: <input type="text" name="ext" maxlength="4" size=4>
  202. </td></tr>
  203. <tr><td>Fax:</td><td>
  204. <input type="text" name="fax" maxlength="15" size=50>
  205. </td></tr>
  206. <tr><td>Email:</td><td>
  207. <input type="text" name="email" maxlength="100" size=60>
  208. </td></tr>
  209. <tr><td>Password:</td><td>
  210. <input type="password" name="pass" maxlength="10" size=12>
  211. </td></tr>
  212. <tr><td>Confirm Password:</td><td>
  213. <input type="password" name="pass2" maxlength="10" size=12>
  214. </td></tr>
  215. <tr><td>Website:</td><td>
  216. <input type="text" name="website" maxlength="100" size=60>
  217. </td></tr>
  218. <tr><td># of Subscribes:</td><td>
  219. <input type="text" name="sub1" maxlength="5" size=4>
  220. </td></tr>
  221. <tr><td># of Addressable Subscribers:</td><td>
  222. <input type="text" name="sub2" maxlength="5" size=4>
  223. </td></tr>
  224. <tr><th colspan=2><input type="submit" name="submit" value="Submit Registeration" ></th></tr> </table>
  225. </form>
  226.  
  227. <?php
  228. }
  229. ?> 
  230.  
  231.  
  232.  
Jul 31 '08 #1
7 2095
Atli
5,058 Recognized Expert Expert
Are you calling the JavaScript function to check the fields after they have been submitted? That won't work. At that point there will be no fields to check.

Try attaching the JavaScript check function to the forms onsubmit event, or the submit buttons onclick event.

Also, the huge regex variable in your JavaScript code contains line-breaks, which is not allowed.
Jul 31 '08 #2
Markus
6,050 Recognized Expert Expert
If the *Javascript* function isn't called, then this *isn't* a PHP problem.
Jul 31 '08 #3
pbmods
5,821 Recognized Expert Expert
If the *Javascript* function isn't called, then this *isn't* a PHP problem.
Agreed. Moving to the JavaScript forum....

Now then.

Try adding an onsubmit handler to your form.
Jul 31 '08 #4
creative1
274 Contributor
I am lost in this combination. I tried everything thing onsubmit() for form, action for form and onlick for submit button. Nothing worked at all except time waste. I alwasy prefer javascript for form validation but now...I dropped the idea to use javascript for php form validation, and used php-form-validation functions for this purpose. It took me a while to write that but that worked . If some want to post how i did that I'll be happy to do that.
Thanks All
Aug 1 '08 #5
gits
5,390 Recognized Expert Moderator Expert
please show how you tried to call the 'checkForm'-method on submit ... the validation must return a boolean value and the line should be similar to the following:

Expand|Select|Wrap|Line Numbers
  1. <form name="my_form" onsubmit="return checkForm();"/>
kind regards
Aug 1 '08 #6
RamananKalirajan
608 Contributor
Hi Dude, this is a simple javascript validation. just try this code this may help you

[HTML]</html>
<head>
<script type="text/javascript">
function validate()
{
var chars = document.getElementById('field').value;
if (chars.length < 130)
{
alert("The news story content must be a minimum of 130 characters to properly display. Please enter more content and re-submit the form.");
return false;
}
else
{
return true;
}
}
</script>
</head>
<form action="demo.html" method="post" onSubmit="return validate()">
<textarea id="field">
</textarea>
<input type="submit" value="Submit Me">
</form>
</html>[/HTML]

Regards
Ramanan Kalirajan
Aug 1 '08 #7
acoder
16,027 Recognized Expert Moderator MVP
I am lost in this combination. I tried everything thing onsubmit() for form, action for form and onlick for submit button. Nothing worked at all except time waste. I alwasy prefer javascript for form validation but now...I dropped the idea to use javascript for php form validation, and used php-form-validation functions for this purpose.
That was a big mistake in the first place. You should never depend on JavaScript validation alone. It's only there as a convenience to avoid unnecessary trips to the server. You MUST have server-side validation at all times.
Aug 1 '08 #8

Sign in to post your reply or Sign up for a free account.

Similar topics

4
1784
by: VbUser25 | last post by:
Hi Please suggest i think i am doing something wrong. I am calling fucntion test from another function where i am performing all the validations.I want to validate the email id. this is the main function where i perform all sort of mandatory validation==> if (document.f.repemail.value != ""){ if(test(document.f.repemail.value=false)) {
6
7123
by: simina | last post by:
Hi... I have a form with 4 number fields: phone area, phone number, cell area, cell number. I did a function that checks the "number" issue for all 4 fields in the same time (because the code is onBlur: "return ph(this);"). Now the problem is that if the user hits Enter data still goes to the database (of course, because I should have the...
16
2194
by: Hosh | last post by:
I have a form on a webpage and want to use JavaScript validation for the form fields. I have searched the web for form validation scripts and have come up with scripts that only validate individual fields, such as an "Email Validation Script" or a "Phone Validation Script". Is it ok to put all these scripts on page as they are or should they...
2
1366
by: Tracey | last post by:
Sorry for the repeated post. I tried to update a record in database using SqlCommand.ExecuteNonQuery( ) method (I failed using SqlDataAdapter). I traced the above statement and found that it returned 1 rows afftected. Then I checked my database, the data was not updated at all Can someone give me a clue ?
1
1398
by: Joey | last post by:
Hi There, I have a page with a form and submit button with validation and on the header of the page I have 2 drop down menus and a submit button, when I select either button it invokes the validation, is it possible to have 2 form buttons on a page doing different things? Joey
7
1470
by: phillip.s.powell | last post by:
Now I have another SQL query for MySQL I can't figure out!! This is overwhelming me completely and I also must have this figured out today and I can't figure it out!! UPDATE student_db.student SET has_letter1 = ( SELECT i.letter1 FROM olddb.student i, student_db student s WHERE s.unique_key = i.unique_key )
9
4153
by: julie.siebel | last post by:
Hello all! As embarrassing as it is to admit this, I've been designing db driven websites using javascript and vbscript for about 6-7 years now, and I am *horrible* at form validation. To be honest I usually hire someone to do it for me, grab predone scripts and kind of hack out the parts that I need, or just do very minimal validation...
1
1616
by: SpiderSwamy | last post by:
Hi, I know little bit about asp, I am facing a problem in Validating the ASP Form.. Example: Stud ID: 501242016 FirstName: Ajit LastName: Kar
2
16776
by: smitanaik | last post by:
hi i want to do validation of datetime in javascripti.e is i want it in this format dd:mm:yyyy:hh:mm:ss plz heklp me out its urgent
0
7177
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
0
7394
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
0
7559
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
1
7123
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
0
7542
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
0
5701
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
0
3248
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
0
3237
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
0
470
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.