Javascript validation with php sample 1 - php

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
<form name="myForm" method="post" onsubmit="return validate();">
First Name : <input type="text" name="fname" id="id_fname"> <br>
Last Name : <input type="text" name="lname" id="id_lname"> <br>
Email : <input type="text" name="email" id="id_email"> <br>
Phone : <input type="text" name="phone" id="id_phone"> <br>
<input type="submit" value="send">
</form>
And below is the javascript code
<script type="text/javascript">
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; }
// now here email validation is not working
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<1 || dotpos<atpos+2 || dotpos+2>=x.length)
alert("Not a valid e-mail address");
return false;
else
return true;
}
// this is for phone number, if this field is empty no validation, if this field not empty it should validate to contain only numbers
else if(document.myForm.id_phone != '') {
var ValidChars = "0123456789";
var IsNumber=true;
var Char;
sText = document.form1.testfield2_phone.value ;
for (i = 0; i < sText.length && 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();
}
</script>
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.
And when a form is submitted, when we refresh then details are resubmitted again, how to avoid this.

Why do you do it so complicated???
if (document.myForm.id_fname.value.length < 3) {
alert("Enter First Name");
return false;
} else if (document.myForm.id_lname.value.length < 3) {
alert("Enter Last Name");
return false;
} else if (!/^\S+#\S+\.\w+$/.test(document.myForm.id_email.value)) {
alert("Not a valid e-mail address");
return false;
} else if (!/^\d+$/.test(document.myForm.id_phone.value)) {
alert("Enter valid Number");
return false;
}
return true;

There are multiple syntax errors, which are mainly related to the else if
For the resubmissions have alook at Post - Redirect - Get (PRG) is a common design pattern for web developers to help avoid certain duplicate form submissions and allow user agents to behave more intuitively with bookmarks and the refresh button.

Related

Input type text array jquery validation

I am new to php and jquery. I want validation for input type text.
<input type="text" size="5" name="add_qnty[]" value="">
I have tried the server side scripting but no use. So please help me
so that my submit will redirect only if all textboxes will fill with data.
Try this:
Add 'class=required' to all the required fields in the form and send these fields as an array to the below function like:
checkFrmFill( $( "#formid").find(".required"));
and the function will be:
function checkFrmFill(inputs) {
var returnVal = true;
for (var i = 0; i < inputs.length; i++) {
if (inputs[i].type == "text" && inputs[i].value == "") {
returnVal = false;
} else if (inputs[i].tagName == "SELECT" && ( inputs[i].value == "select" || inputs[i].value == 0 ) || inputs[i].value == "" || inputs[i].value == null) {
returnVal = false;
} else if (inputs[i].type == "password" && inputs[i].value == "") {
returnVal = false;
} else if (inputs[i].type == "textarea" && inputs[i].value == "") {
returnVal = false;
}
}
return returnVal;
}
This will return false for those fields that are blank.
For every text input add required attribute at the end of the tag.
<input type="text" size="5" name="add_qnty[]" value="" required>
<input type="text" size="5" name="add_qnty[]" value="" required>
refer http://www.w3schools.com/tags/att_input_required.asp
HTML
...........................
form id ='frm'
submit button id ='submit_frm'
SCRIPT
.............................
$(function(){
$('#submit_frm').click(function(){
$('#frm').find('em.err').remove();
$('#frm').find('input[type=text]').each(function(){
if($(this).val()==''){
$(this).parent().append('<em class="err">This field is required</em>');
}
});
if($('#frm').find('em.err').length > 0 ){
return false;
}else{
return true;
}
});
});
Try this: Working Example JSFIDDLE
$("form").on("submit",function(){
var len = $("input[name='add_qnty[]']").filter(function() {
return !this.value;
}).addClass("has-error").length;
alert(len);
if(len == 0){
return true; // Submit form
} else {
return false; // Validation failed
}
})

Contact form with Jquery and PHP

Attempting to set up a Jquery and PHP Contact form on my website found here http://www.greenlite.co.uk/Contactus.html
I think I'm doing something wrong with the PHP file. I've put the necessary email into the PHP file but I'm not sure if I've linked it in the main code correctly, or even how to do that. Or even where to add it on the root file.
Here's the code I'm using;
<!DOCTYPE HTML>
<html>
<head>
<title>Contact Form</title>
<link href="js/style.css" rel="stylesheet" />
<script type="text/javascript" src="js/jquery-1.9.0.min.js"></script>
<script type="text/javascript" src="js/contact/jquery.validate.min.js"></script>
<script type="text/javascript" src="js/contact/jquery.form.js"></script>
<script type="text/javascript" src="js/contact.js"></script>
</head>
<body>
<div id="wrap">
<h1>Contact Greenlite Controls</h1>
<form id="contactform" action="processForm.php" method="post">
<table>
<tr>
<td><label for="name">Name:</label></td>
<td><input type="text" id="name" name="name" /></td>
</tr>
<tr>
<td><label for="email">Email:</label></td>
<td><input type="text" id="email" name="email" /></td>
</tr>
<tr>
<td><label for="message">Message:</label></td>
<td><textarea id="message" name="message" rows="5" cols="20"></textarea></td>
</tr>
<tr>
<td></td>
<td><input type="submit" value="Send" id="send" /></td>
</tr>
</table>
</form>
<div id="response"></div>
</div>
</body>
</html>
And here is the PHP
<?php
// Clean up the input values
foreach($_POST as $key => $value) {
if(ini_get('magic_quotes_gpc'))
$_POST[$key] = stripslashes($_POST[$key]);
$_POST[$key] = htmlspecialchars(strip_tags($_POST[$key]));
}
// Assign the input values to variables for easy reference
$name = $_POST["name"];
$email = $_POST["email"];
$message = $_POST["message"];
// Test input values for errors
$errors = array();
if(strlen($name) < 2) {
if(!$name) {
$errors[] = "You must enter a name.";
} else {
$errors[] = "Name must be at least 2 characters.";
}
}
if(!$email) {
$errors[] = "You must enter an email.";
} else if(!validEmail($email)) {
$errors[] = "You must enter a valid email.";
}
if(strlen($message) < 10) {
if(!$message) {
$errors[] = "You must enter a message.";
} else {
$errors[] = "Message must be at least 10 characters.";
}
}
if($errors) {
// Output errors and die with a failure message
$errortext = "";
foreach($errors as $error) {
$errortext .= "<li>".$error."</li>";
}
die("<span class='failure'>The following errors occured:<ul>". $errortext ."</ul> </span>");
}
// Send the email
$to = "mick#greenlite.co.uk";
$subject = "Contact Form: $name";
$message = "$message";
$headers = "From: $email";
mail($to, $subject, $message, $headers);
// Die with a success message
die("<span class='success'>Success! Your message has been sent.</span>");
// A function that checks to see if
// an email is valid
function validEmail($email)
{
$isValid = true;
$atIndex = strrpos($email, "#");
if (is_bool($atIndex) && !$atIndex)
{
$isValid = false;
}
else
{
$domain = substr($email, $atIndex+1);
$local = substr($email, 0, $atIndex);
$localLen = strlen($local);
$domainLen = strlen($domain);
if ($localLen < 1 || $localLen > 64)
{
// local part length exceeded
$isValid = false;
}
else if ($domainLen < 1 || $domainLen > 255)
{
// domain part length exceeded
$isValid = false;
}
else if ($local[0] == '.' || $local[$localLen-1] == '.')
{
// local part starts or ends with '.'
$isValid = false;
}
else if (preg_match('/\\.\\./', $local))
{
// local part has two consecutive dots
$isValid = false;
}
else if (!preg_match('/^[A-Za-z0-9\\-\\.]+$/', $domain))
{
// character not valid in domain part
$isValid = false;
}
else if (preg_match('/\\.\\./', $domain))
{
// domain part has two consecutive dots
$isValid = false;
}
else if(!preg_match('/^(\\\\.|[A-Za-z0-9!#%&`_=\\/$\'*+?^{}|~.-])+$/',
str_replace("\\\\","",$local)))
{
// character not valid in local part unless
// local part is quoted
if (!preg_match('/^"(\\\\"|[^"])+"$/',
str_replace("\\\\","",$local)))
{
$isValid = false;
}
}
if ($isValid && !(checkdnsrr($domain,"MX") || checkdnsrr($domain,"A")))
{
// domain not found in DNS
$isValid = false;
}
}
return $isValid;
}
?>
Basically if it's not clear, after I use the contact form I get "Sending" but it does not die. I don't get a Success message and the mail doesn't send. I can only assume it's something to do with the PHP.
I've put the PHP file into a folder on the root called php and tried to call it from "action="php/ProcessForm.php" but this didn't make a difference.
Why do you do not validate the form with Jquery, instead inside the PHP??
Try to use AJAX to send your form and Jquery UI to response your user with the sucess or failure.
Try to use the .serialize() (http://api.jquery.com/serialize/) function in query and $.ajax.
This way, you'll can clean up your php file and find the error.
Look a simple example of the code:
Call the submit funcion:
$().ready(function(e) {
$("#cad_cliente").submit(function(e){
e.preventDefault();
insertDataForm(getDataForm());
});
return false;
});
Serialize the parameters:
function getDataForm(){
var params=$("#cad_cliente").serialize();
return params;
}
Post the values in your php file:
$.ajax({
type: 'post',
url:'registra.php',
data:params,
cache:false,
success: function(){
Alert("mesenge");
}
});
}
Glad if i could help you...

JS form validation not working

I'm trying to validate some form fields using JS functions, but they don't seem to load or check the field when the submit button is clicked.
<html>
<body>
<?php require_once('logic.php'); ?>
<h1>Add new Region/Entity</h1>
<?php
if ($_POST['submitted']==1) {
echo $error;
}
?>
<form action="logic.php" method="post" name="registration" onSubmit="return formValidation();">
Region: <input type="text" name="region" value="<?php echo #$_POST['region']; ?>"><br>
Description: <br><textarea name="description" cols="50" rows="10"><?php echo #$_POST['description']; ?></textarea><br>
Remarks: <input type="text" name="remarks" value="<?php echo #$_POST['remarks']; ?>">
<input type="hidden" name="submitted" value="1"><br>
<input type="submit" value="Submit" onclick="">
And here's the JS:
<script type="text/javascript">
function formValidation() {
var region = document.registration.region;
var descr = document.registration.description;
var remarks = document.registration.remarks;
if(empty_validation()) {
if(reg_validation()) {
if(reg_letters()) {
if (desc_letters()) {
if (desc_validation()) {
}
}
}
}
}
return false;
}
function empty_validation() {
var reg_len = region.value.length;
var descr_len = descr.value.length;
var rem_len = remarks.value.length;
if (reg_len == 0 || decr_len == 0 || rem_len == 0) {
alert("Please fill all the fields");
return false;
}
return true;
}
function reg_validation() {
if (reg_len > 50) {
alert("Only 50 characters are allowed in the Region field");
region.focus();
return false;
}
return true;
}
function reg_letters() {
var letters = /^[A-Za-z]+$/;
if(region.value.match(letters)) {
return true;
} else {
alert('Region field must have only alphabetical characters');
region.focus();
return false;
}
}
function desc_validation() {
if (descr_len > 500) {
alert("Only 500 characters are allowed in the description field");
descr.focus();
return false;
}
return true;
}
function desc_letters() {
var iChars = "!##$%^&*()+=-[]\\\';,./{}|\":<>?";
for (var i = 0; i < descr_len; i++) {
if (iChars.indexOf(descr.value.charAt(i)) != -1) {
alert ("Your description has special characters. \nThese are not allowed.\n Please remove them and try again.");
return false;
}
}
return true;
}
</script>
</form>
</body>
</html>
As you can see, I'm posting values from the form to a PHP file. And I've used the onSubmit event in the form tag to initialize the formValidation() function. It isn't working for some reason.
Here's a working example if you need one.
I'm not going to fix every little error you have, but the main problem is that variables aren't defined where you expect them to be. You can't declare a variable in one function and expect it to be available in the next (without passing it as a parameter or declaring it globally). For example, your empty_validation function should be this:
function empty_validation(region, descr, remarks) {
var reg_len = region.value.length;
var descr_len = descr.value.length;
var rem_len = remarks.value.length;
if (reg_len == 0 || decr_len == 0 || rem_len == 0) {
alert("Please fill all the fields");
return false;
}
return true;
}
And in your formValidation function, you call it like this:
if(empty_validation(region, descr, remarks)) {
This is just one example, and you would need to do it in a few places.
A few other things - you always return false from formValidation...did you mean to put return true; inside the innermost if statement? Also, since all you seem to be doing is calling each of those functions, you can probably put them into one big if statement, like this:
if (empty_validation() && reg_validation() && reg_letters() && desc_letters() && desc_validation()) {
return true;
}
return false;

I can't get my form to validate AND submit using jQuery validation

I have been digging around on here and other sites for a while and am stuck. I'm trying to use jQuery to validate my form (concurrently as the user fills out the form) and, if the form is valid have it submit to a php page I have created to process the contents of the form. I have been able to have it validate but I can't have it also submit it...if I put a value in for the form action parm then it bypasses the validation. Please help...
I apologize, in advance, for the bad coding.
Here is my jquery-validate.js:
//global vars
var form = $("#customForm");
var name = $("#name");
var nameInfo = $("#nameInfo");
var email = $("#email");
var emailInfo = $("#emailInfo");
var pass1 = $("#pass1");
var pass1Info = $("#pass1Info");
var pass2 = $("#pass2");
var pass2Info = $("#pass2Info");
var message = $("#message");
function validateName(){
//if it's NOT valid
if(name.val().length < 4){
name.addClass("error");
nameInfo.text("We want names with more than 3 letters!");
nameInfo.addClass("error");
return false;
}
//if it's valid
else{
name.removeClass("error");
nameInfo.text("What's your name?");
nameInfo.removeClass("error");
return true;
}
}
function validatePass1(){
var a = $("#password1");
var b = $("#password2");
//it's NOT valid
if(pass1.val().length <5){
pass1.addClass("error");
pass1Info.text("Ey! Remember: At least 5 characters: letters, numbers and '_'");
pass1Info.addClass("error");
return false;
}
//it's valid
else{
pass1.removeClass("error");
pass1Info.text("At least 5 characters: letters, numbers and '_'");
pass1Info.removeClass("error");
validatePass2();
return true;
}
}
function validatePass2(){
var a = $("#password1");
var b = $("#password2");
//are NOT valid
if( pass1.val() != pass2.val() ){
pass2.addClass("error");
pass2Info.text("Passwords doesn't match!");
pass2Info.addClass("error");
return false;
}
//are valid
else{
pass2.removeClass("error");
pass2Info.text("Confirm password");
pass2Info.removeClass("error");
return true;
}
}
function validateMessage(){
//it's NOT valid
if(message.val().length < 10){
message.addClass("error");
return false;
}
//it's valid
else{
message.removeClass("error");
return true;
}
}
/*
Validate the name field in: blur and keyup events.
Validate the email field in: blur event.
Validate the password fields in: blur and keyup events.
Validate the message field in: blur, and keyup event.
Validate all fields in: submit form event
*/
//On blur
name.blur(validateName);
email.blur(validateEmail);
pass1.blur(validatePass1);
pass2.blur(validatePass2);
//On key press
name.keyup(validateName);
pass1.keyup(validatePass1);
pass2.keyup(validatePass2);
message.keyup(validateMessage);
//On Submitting
form.submit(function(){
if(validateName() && validateEmail() && validatePass1() && validatePass2() && validateMessage())
return true;
else
return false;
});
My form code is pasted here:
<form method="post" id="customForm" action="rcv-form1.php">
<div>
<label for="name">Name</label>
<input id="name" name="name" type="text" />
<span id="nameInfo">What's your name?</span>
</div>
<div>
<label for="email">E-mail</label>
<input id="email" name="email" type="text" />
<span id="emailInfo">Valid E-mail please, you will need it to log in!</span>
</div>
<div>
<label for="pass1">Password</label>
<input id="pass1" name="pass1" type="password" />
<span id="pass1Info">At least 5 characters: letters, numbers and '_'</span>
</div>
<div>
<label for="pass2">Confirm Password</label>
<input id="pass2" name="pass2" type="password" />
<span id="pass2Info">Confirm password</span>
</div>
<div>
<label for="message">Message</label>
<textarea id="message" name="message" cols="" rows=""></textarea>
</div>
<div>
<input id="send" name="send" type="submit" value="Send" />
</div>
</form>
And here is my php that receives the form (this is just for testing now. i will email or insert into mySQL once i know i can properly validate stuff):
<html><head>
<title>Display form values</title>
</head>
<body>
<?
//$valid_form = TRUE;
//$bad_field_count = 0;
$table1_beg = '<center><table align="center" bordercolor="#F00" width="600px" border="3" cellspacing="1" cellpadding="1"><caption>Form status</caption><tr><th scope="col">Field Name</th><th scope="col">Field Value</th></tr>';
$row_beg = '<tr><td>';
$td = '</td><td>';
$row_end = '</td></tr>';
$table1_end = '</table></center>';
function checkEmail($field)
{
if (filter_var($field, FILTER_VALIDATE_EMAIL)) {
//echo "This ($field) email address is considered valid.";
return $field;
} else {
$field = filter_var($field, FILTER_SANITIZE_EMAIL);
//global $bad_field_count; $bad_field_count++;
return $field;
}
}
function SanitizeString($field)
{
$field = filter_var($field, FILTER_SANITIZE_STRING);
//if(is_null($field) || $field == '') { global $bad_field_count; $bad_field_count++;}
return $field;
}
// ensure form data is valid
$name=SanitizeString($_POST['name']);
//$email=$_POST['email'];
$email = checkEmail($_POST['email']);
$pass1=SanitizeString($_POST['pass1']);
$pass2=SanitizeString($_POST['pass2']);
$message=SanitizeString($_POST['message']);
echo $table1_beg;
echo $row_beg . "Name" . $td . "<u>" . $name . "</u>" . $row_end;
echo $row_beg . "Email" . $td . "<u>" . $email . "</u>" . $row_end;
echo $row_beg . "Password 1" . $td . "<u>" . $pass1 . "</u>" . $row_end;
echo $row_beg . "Password 2" . $td . "<u>" . $pass2 . "</u>" . $row_end;
echo $row_beg . "Message" . $td . "<u>" . nl2br($message) . "</u>" . $row_end;
//echo $row_beg . "Number of bad fields" . $td . "<b>" . $bad_field_count . "</b>" . $row_end;
echo $table1_end;
//}
?>
</body></html>
Problem 1: When I have form action="" I can validate the form only after hitting submit...it doesn't say it's invalid until after submitting when I thought it should do it concurrently as it is typed in.
Problem 2: If I have my form action set to anything but "" it will ignore the jQuery validation all together.
I'm new to the form validation stuff. Can someone point me in the right direction? Thanks, in advance!
You have a few problems, your form submit code doesn't have curly brackets around it, and you don't have a function for validate email, try this:
//global vars
var form = $("#customForm");
var fname = $("#name");
var nameInfo = $("#nameInfo");
var email = $("#email");
var emailInfo = $("#emailInfo");
var pass1 = $("#pass1");
var pass1Info = $("#pass1Info");
var pass2 = $("#pass2");
var pass2Info = $("#pass2Info");
var message = $("#message");
function validateName() {
//if it's NOT valid
if (fname.val().length < 4) {
fname.addClass("error");
nameInfo.text("We want names with more than 3 letters!");
nameInfo.addClass("error");
return false;
}
//if it's valid
else {
fname.removeClass("error");
nameInfo.text("What's your name?");
nameInfo.removeClass("error");
return true;
}
}
function validatePass2() {
var a = $("#password1");
var b = $("#password2");
//are NOT valid
if (pass1.val() != pass2.val()) {
pass2.addClass("error");
pass2Info.text("Passwords doesn't match!");
pass2Info.addClass("error");
return false;
}
//are valid
else {
pass2.removeClass("error");
pass2Info.text("Confirm password");
pass2Info.removeClass("error");
return true;
}
}
function validatePass1() {
var a = $("#password1");
var b = $("#password2");
//it's NOT valid
if (pass1.val().length < 5) {
pass1.addClass("error");
pass1Info.text("Ey! Remember: At least 5 characters: letters, numbers and '_'");
pass1Info.addClass("error");
return false;
}
//it's valid
else {
pass1.removeClass("error");
pass1Info.text("At least 5 characters: letters, numbers and '_'");
pass1Info.removeClass("error");
validatePass2();
return true;
}
}
function validateMessage() {
//it's NOT valid
if (message.val().length < 10) {
message.addClass("error");
return false;
}
//it's valid
else {
message.removeClass("error");
return true;
}
}
function validateEmail(){
//add validation for email here
return true;
}
/*
Validate the name field in: blur and keyup events.
Validate the email field in: blur event.
Validate the password fields in: blur and keyup events.
Validate the message field in: blur, and keyup event.
Validate all fields in: submit form event
*/
//On blur
fname.blur(validateName);
email.blur(validateEmail);
pass1.blur(validatePass1);
pass2.blur(validatePass2);
//On key press
fname.keyup(validateName);
pass1.keyup(validatePass1);
pass2.keyup(validatePass2);
message.keyup(validateMessage);
//On Submitting
form.submit(function() {
if (validateName() && validateEmail() && validatePass1() && validatePass2() && validateMessage()) {
return true;
}
else {
return false;
}
});
I've gave you an easy way to validate your all inputs/textarea within one function but you have to complete it, I've just gave you the structure and only name validation has done as an example for you and I hope you can understand it easily. If you need more help/difficulties just leave a message. This should be placed inside ready event.
var info={
'nameInfo':$("#nameInfo"),
'emailInfo':$("#emailInfo"),
'pass1Info':$("#pass1Info"),
'pass2Info':$("#pass2Info")
}
$('#customForm input,textarea').not("#send").bind('blur keyup', function(e)
{
e.stopPropagation();
var el=$(e.target);
var id=el.attr('id');
if(el.attr('id')=='message' && e.type=="keyup")
{
return false;
}
else
{
if(id=="name")
{ if(el.val().length < 4)
{
el.addClass("error");
info.nameInfo.text("We want names with more than 3 letters!");
info.nameInfo.addClass("error");
return false;
}
else
{
el.removeClass("error");
info.nameInfo.text("What's your name ?");
info.nameInfo.removeClass("error");
return true;
}
}
if(id=="email")
{
// Your email validation code
}
if(id=="pass1")
{
// Your pass1 validation code
}
if(id=="pass2")
{
// Your pass2 validation code
}
if(id=="message")
{
// Your message validation code
}
}
});

HTML form validation

I created a simple HTML form which takes input as username of the customer. It validates if it is indeed a valid username or not. If yes then it should go to the step2.php page if not then it should display an error and stay on the original page.
Here is my HTML code:
<form method="post" onsubmit="validateUsername();" id="myform" name="myform" action="step2.php">
Choose username: <input type="text" id="username" name="username" />
<input type="submit" value="Submit">
</form>
I am validating username by using a javascript function:
function validateUsername()
{
var x=document.forms["myform"]["username"].value.length;
if (x < 5)
{
alert('Username too short.');
return false;
}
else
{
return true;
}
}
My problem:
If the user enters a short username then it displays an alert message "Username too short". When I press "OK" button on alert message then it is going to step2.php. Ideally it should send data to step2.php only when username is validated correctly. But this is not happening.
Anyone able to find the bug in my code?
Change:
<form method="post" onsubmit="validateUsername();" id="myform" name="myform" action="step2.php">
Choose username: <input type="text" id="username" name="username" />
<input type="submit" value="Submit">
</form>
To:
<form method="post" onsubmit="return validateUsername();" id="myform" name="myform" action="step2.php">
Choose username: <input type="text" id="username" name="username" />
<input type="submit" value="Submit">
</form>
Note the addition of the keyword return which should cancel the form from submitting if validateUsername returns false.
Try this. (Add return to onsubmit in the form)
<form method="post" onsubmit="return validateUsername();" id="myform" name="myform" action="step2.php">
Choose username: <input type="text" id="username" name="username" />
<input type="submit" value="Submit">
</form>
Also on another note, make sure you also validate this trough php in step2, since client-side validation can be easily bypassed.
Add return before calling the function:
onsubmit="return validateUsername();"
..or use event.preventDefault():
onsubmit="if(!validateUsername()) event.preventDefault();"
First your html form, do not use return before javascript function in onsubmit event of form
<form method="post" onsubmit="validateUsername();" id="myform" name="myform" action="step2.php">
Choose username: <input type="text" id="username" name="username" />
<input type="submit" value="Submit">
Now javascript function, you have to give only one condition if username is less then 5 char it will not submit form otherwise it will submit form and post data to step2.php
function validateUsername()
{
var x=document.myform.username.value.length;
if (x < 5)
{
alert('Username too short.');
return false;
}
}
function validation(){
var eid=$.trim($('#email').val());
var password=$.trim($('#password').val());
var emailval =/^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z])+/;
var con=/^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/;
var errmsg='';
var c=0;
var cur_el='';
if(eid=='' || eid==null)
{
errmsg="enter your email";
cur_el=$('#email');
c=1;
}
else if (!emailval.test(eid)) {
errmsg="Please provide a valid email address (hints : daskoushik9#gmail.com)";
cur_el=$('#email');
c=1;
}
else if(password=='')
{
errmsg="enter password";
cur_el=$('#password');
c=1;
}
else if(password.length<4)
{
errmsg="password is too short";
cur_el=$('#password');
c=1;
}
if(c==1 && errmsg!=''){
alert(errmsg);
cur_el.focus();
return false;
}
else
{return true;}
}
function adminprofilevalidation(){
var ad_uname=$.trim($('#admin_username').val());
var ad_oldpass=$.trim($('#admin_passo').val());
var ad_newpass=$.trim($('#admin_pass').val());
var ad_repass=$.trim($('#admin_passc').val());
var ad_email=$.trim($('#admin_email').val());
// var eid=$.trim($('#email').val());
// var password=$.trim($('#password').val());
// var cpassword=$.trim($('#cpassword').val());
// var file=$('#file').val();
var errmsg='';
var c=0;
var cur_el='';
//var em=/^([a-zA-Z0-9_.-])+#([a-zA-Z0-9_.-])+\.([a-zA-Z])+([a-zA-Z])+/;
var alphaExp = /^[a-zA-Z]+$/;
// var alphaNum = /^[0-9a-zA-Z]+$/;
// var digit = /^[0-9]+$/;
// var fdigit=/^[0]+$/;
var emailval = /^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z])+/;
var con=/^\(?([0-9]{2})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/;
if(ad_uname=='' || ad_uname==null)
{
errmsg="Enter User name";
cur_el=$('#admin_username');
c=1;
}
else if(!ad_uname.match(alphaExp)){
errmsg="Please enter only letters for your name";
cur_el=$('#firstname');
c=1;
}
else if(ad_oldpass=='' || ad_oldpass==null)
{
errmsg="enter Old password";
cur_el=$('#admin_passo');
c=1;
} else if(ad_oldpass.length<4)
{
errmsg="password is too short";
cur_el=$('#admin_passo');
c=1;
}
else if(ad_newpass=='' || ad_newpass==null)
{
errmsg="please enter new password";
cur_el=$('#admin_pass');
c=1;
}
else if(ad_newpass.length<4)
{
errmsg="password is too short";
cur_el=$('#admin_pass');
c=1;
}
else if(ad_repass=='' || ad_repass==null)
{
errmsg="please re enter the password";
cur_el=$('#admin_passc');
c=1;
}
else if(ad_repass.length<4)
{
errmsg="password is too short";
cur_el=$('#admin_passc');
c=1;
}
else if(ad_email=='' || ad_email==null)
{
errmsg="Enter your email";
cur_el=$('#admin_email');
c=1;
}
else if (!emailval.test(ad_email)) {
errmsg='Please provide a valid email address (hints : daskoushik9#gmail.com)';
cur_el=$('#admin_email');
c=1;
}
if(c==1 && errmsg!=''){
alert(errmsg);
cur_el.focus();
return false;
}
else
{return true;}
}
function companyprofilevalidation(){
var co_name=$.trim($('#company_name').val());
var co_pcntact=$.trim($('#company_contact_person').val());
var co_add=$.trim($('#company_address').val());
var co_phn=$.trim($('#company_phone').val());
var co_email=$.trim($('#company_email').val());
var errmsg='';
var c=0;
var cur_el='';
//var em=/^([a-zA-Z0-9_.-])+#([a-zA-Z0-9_.-])+\.([a-zA-Z])+([a-zA-Z])+/;
var alphaExp = /^[a-zA-Z]+$/;
// var alphaNum = /^[0-9a-zA-Z]+$/;
var digit = /^[0-9]+$/;
var fdigit=/^[0]+$/;
var emailval = /^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z])+/;
var con=/^\(?([0-9]{2})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/;
if(co_name=='' || co_name==null)
{
errmsg="Enter Company name";
cur_el=$('#company_name');
c=1;
}
else if(co_pcntact=='' || co_pcntact==null)
{
errmsg="enter Person Contact name";
cur_el=$('#company_contact_person');
c=1;
}
else if(co_add=='' || co_add==null)
{
errmsg="please enter company address";
cur_el=$('#company_address');
c=1;
}
else if(co_phn=='' || co_phn==null)
{
errmsg="please enter company phone no";
cur_el=$('#company_phone');
c=1;
}
else if(fdigit.test(co_phn)){
errmsg="first digit must be non zero";
cur_el=$('#company_phone');
c=1;
}
else if(co_phn.length<10)
{
errmsg="please give 10 digit no";
cur_el=$('#company_phone');
c=1;
}
else if(co_email=='' || co_email==null)
{
errmsg="Enter your email";
cur_el=$('#company_email');
c=1;
}
else if (!emailval.test(co_email)) {
errmsg='Please provide a valid email address (hints : daskoushik9#gmail.com)';
cur_el=$('#company_email');
c=1;
}
if(c==1 && errmsg!=''){
alert(errmsg);
cur_el.focus();
return false;
}
else
{return true;}
// else if(file=='')
// {
// errmsg="upload your photo";
// cur_el=$('#uploadfile');
// c=1;
// }
// else if(fdigit.test(phone)){
// errmsg="first digit must be non zero";
// cur_el=$('#phone');
// c=1;
// }
}
function jobaddvalidation(){
var errmsg='';
var c=0;
var cur_el='';
//var em=/^([a-zA-Z0-9_.-])+#([a-zA-Z0-9_.-])+\.([a-zA-Z])+([a-zA-Z])+/;
var alphaExp = /^[a-zA-Z]+$/;
// var alphaNum = /^[0-9a-zA-Z]+$/;
var digit = /^[0-9]+$/;
var fdigit=/^[0]+$/;
var emailval = /^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z])+/;
var con=/^\(?([0-9]{2})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/;
var jtitle=$.trim($('#job_title').val());
var jsummery=$.trim($('#job_summery').val());
// var jdescription=$.trim($('#job_description').val());
var cid=$.trim($('#category_id').val());
var jreq=$.trim($('#job_requirements').val());
var jcdetails=$.trim($('#job_contact_details').val());
var jcpname=$.trim($('#job_contact_person_name').val());
var jcpemail=$.trim($('#job_contact_person_email').val());
var jacdetails=$.trim($('#job_additional_contact_details').val());
var jscopy='';
if(document.form1.job_scan_copy.checked){
jscopy=$.trim($('#job_scan_copy').val());
}
var jnscopy='';
jnscopy=$.trim($('#job_no_scan_copy').val());
var jloc=$.trim($('#job_location').val());
var jctc=$.trim($('#job_ctc').val());
var jureq=$.trim($('#job_upload_requirement').val());
if(jtitle==null || jtitle=='')
{
errmsg="please give job title";
cur_el=$('#job_title');
c=1;
}else if(jsummery==null || jsummery=='')
{
errmsg="please give job summery ";
cur_el=$('#job_summery');
c=1;
}
// else if(jdescription==null || jdescription=='')
// {
// errmsg="please mention job description";
// cur_el=$('#job_description');
// c=1;
// }
else if(cid==null || cid=='')
{
errmsg="please give category name";
cur_el=$('#category_id');
c=1;
}else if(jreq==null || jreq=='')
{
errmsg="please give job requirement";
cur_el=$('#job_requirements');
c=1;
}
else if(jcdetails==null || jcdetails=='')
{
errmsg="please give job contact details";
cur_el=$('#job_contact_details');
c=1;
}else if(jcpname==null || jcpname=='')
{
errmsg="please give job contact person name";
cur_el=$('#job_contact_person_name');
c=1;
}else if(jcpemail==null || jcpemail=='')
{
errmsg="please give job contact person email";
cur_el=$('#job_contact_person_email');
c=1;
}else if(!emailval.test(jcpemail))
{
errmsg="please give valid job contact person email";
cur_el=$('#job_contact_person_email');
c=1;
}else if(jacdetails==null || jacdetails=='')
{
errmsg="please give job additional contact details";
cur_el=$('#job_additional_contact_details');
c=1;
}else if((jscopy!='' && jnscopy=='') || (jscopy=='' && jnscopy!=''))
{
errmsg="please give both scan copy and no scan copy OR both un select";
cur_el=$('#job_scan_copy');
c=1;
}else if(jloc==null || jloc=='')
{
errmsg="please mention job location";
cur_el=$('#job_location');
c=1;
}else if(jctc==null || jctc=='')
{
errmsg="please mention job C T C";
cur_el=$('#job_ctc');
c=1;
}
if(c==1 && errmsg!=''){
alert(errmsg);
cur_el.focus();
return false;
}
else
{return true;}
}

Categories