jquery validations are not working when i click on submit button - php

I have written a html form and jquery to perform the validations. But when i click the submit button, nothing is happening. I can't understand what is going on, whether the form is linking up with the jquery file or not. Please any check my code and help me.
index.html
<html>
<head>
<title>validation</title>
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript" src="js/custom.js"></script>
</head>
<body>
<form action="" method="post" id="reg_form">
<p>Name:</p>
<p><input id="name" name="name" type="text"></p>
<p>What's your name?</p>
<p>Email:</p>
<p><input id="email" name="email" type="text"></p>
<p>Enter mail id</p>
<p>Password:</p>
<p><input id="pass1" name="pass1" type="password"></p>
<p>More than 8 characters</p>
<p>Password:</p>
<p><input id="pass2" name="pass2" type="password"></p>
<p>same as above</p>
<p>phone</p>
<p><input id="phone" name="phone" type="text"></p>
<p>What's your number?</p>
<input id="submit" name="submit" type="submit" value="submit"/>
</form>
</body>
</html>
custom.js
$(document).ready(function(){
var form = $("#reg_form");
var name = $("#name");
var nameDetails = $("#nameDetails");
var email = $("#email");
var emailDetails = $("#emailDetails");
var pass1 = $("#pass1");
var pass2 = $("#pass2");
var pass1Details = $("#pass1Details");
var pass2Details = $("#pass2Details");
var phone = $("#phone");
var phoneDetails = $("#phoneDetails");
var button = $("#submit");
name.blur(validateName);
email.blur(validateEmail);
pass1.blur(validatePass1);
pass2.blur(validatePass2);
phone.blur(validatePhone);
name.keyup(validateName);
email.keyup(validateEmail);
pass1.keyup(validatePass1);
pass2.keyup(validatePass2);
phone.keyup(validatePhone);
form.submit(function(){
if(validateName() & validateEmail & validatePass1 & validatePass2() & validatePhone()){
return true;
}else{
return false;
}
});
function validateName(){
if(name.val().length<5){
name.addClass("error");
nameDetails.text("Your name should have atleast 5 characters");
nameInfo.addClass("error");
return false;
}else{
name.removeClass("error");
nameDetails.text("Whats your name?");
}
}
function validateEmail(){
var a = $("#email").val();
var regexp = /^[a-zA-Z0-9]+[a-zA-Z0-9_.-]+[a-za-zA-Z0-9_-]+#[a-zA-Z0-9]+[a-zA-Z0-9.-]+[a-zA-Z0-9]+.[a-z]{2,4}$/;
if(filter.text(a)){
email.removeClass("error");
emailDetails.text("Enter mail id");
emailDetails.removeClass("error");
return true;
}else{
email.addClass("error");
emailDetails.text("Enter valid mail id");
emailDetails.addClass("error");
}
}
function validatePass1(){
if(pass1.val().length<8){
pass1.addClass("error");
pass1Details.text("8 characters or more");
pass1Details.addClass("error");
return false;
}else{
pass1.removeClass("error");
pass1.Details.text("Enter mail id");
pass1.Details.removeClass("error");
return true;
}
}
function validatePass2(){
if(pass2.val().length < 1){
pass2.addClass("error");
pass2Details.text("8 characters or more");
pass2Details.addClass("error");
return false;
}
if(pass1.val()!== pass2.val()){
pass2.addClass("error");
pass2Details.text("8 characters or more");
pass2Details.addClass("error");
return false;
}else{
pass2.removeClass("error");
pass2.Details.text("Same as above");
pass2.Details.removeClass("error");
return true;
}
}
function validatePhone(){
var b = $("#phone").val();
var regexp = /[0-9]{10}/;
if(filter.text(b)){
email.removeClass("error");
emailDetails.text("Enter phone number");
emailDetails.removeClass("error");
return true;
}else{
email.addClass("error");
emailDetails.text("Enter valid phone number");
emailDetails.addClass("error");
}
}
});

use the statements like this,
var name = $("#name ").val();
Or
var name = jQuery("#name ").val();
and then try...it will work...

Try this
$(document).ready(function(){
var form = $("#reg_form").val();
var name = $("#name").val();
...
});

Try this..
$(document).ready(function(){
var name = $("#name").val();
var nameDetails = $("#nameDetails").val();
var email = $("#email").val();
var emailDetails = $("#emailDetails").val();
var pass1 = $("#pass1").val();
var pass2 = $("#pass2").val();
var pass1Details = $("#pass1Details").val();
var pass2Details = $("#pass2Details").val();
var phone = $("#phone").val();
var phoneDetails = $("#phoneDetails").val();
});

Related

Jquery form validation Name...It must contain all characters... Help me out

name is Name id
submit is Submit id
help me to convert the code to check it contains all characters(no number and no special characters)
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('.form_error').hide();
$('#submit').click(function(){
var name = $('#name').val();
if(name== '') {
$('#name').next().show();
return false;
} else {
return true;
}
//ajax call php page
$.post("send.php",
$("#contactform").serialize(), function(response) {
$('#contactform').fadeOut('slow',function(){
});
});
return false;
});
});
</script>
<form action="" method="post" id="contactform">
Name: <input name="name" id="name" type="text"
placeholder="Please enter your name" class="contact-input">
<span class="form_error"> Please enter your valid name</span>
<br><br>
<input type="submit" class="contactform-buttons" id="submit"value="Send" />
</form>
</html>
name is Name id
submit is Submit id
Help me to convert the code to check it contains all characters(no number and no special characters)
$(function() {
$('#name').keypress(function (e) {
var regex = new RegExp("^[a-zA-Z]+$");
var str = String.fromCharCode(!e.charCode ? e.which : e.charCode);
if (regex.test(str)) {
return true;
}
else
{
e.preventDefault();
alert('Please enter only alphabet');
return false;
}
});
});
Alternative Method:
$(function() {
$('#name').keydown(function(e) {
if (e.shiftKey || e.ctrlKey || e.altKey) {
e.preventDefault();
} else {
var key = e.keyCode;
if (!((key == 8) || (key == 32) || (key == 46) || (key >= 35 && key <= 40) || (key >= 65 && key <= 90))) {
e.preventDefault();
}
}
});
});

Ajax email address validator

Currently the below script works brillantly checking the database using ajax to see if the email address has been used before. My question is how do I stop it checking the database until it is a fully defined EMAIL address?
Form field
<label for="email">Email: * </label><br/>
<input id="username" name="username" type="email" value="" onblur="return check_username();" />
AJAX script
<script type="text/javascript">
$(document).ready(function() {
$('#Loading').hide();
});
function check_username(){
var username = $("#username").val();
if(username.length > 2){
$.post("../script/check_username_availablity.php", {
username: $('#username').val(),
}, function(response){
$('#Info').fadeOut();
setTimeout("finishAjax('Info', '"+escape(response)+"')", 450);
});
return false;
}
}
function finishAjax(id, response){
$('#'+id).html(unescape(response));
$('#'+id).fadeIn(1000);
}
</script>
Instead of if(username.length > 2){... use something like:
if (/^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\
".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA
-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/.test(username.val())) {...
see http://jsfiddle.net/cmontgomery/gEL7n/
very similar to what ialencar posted:
isValidateEmail = function(email) {
var re = /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(email);
}
check_username = function() {
var username = $("#username").val();
if(isValidateEmail(username)) {
$("#username-error").html("");
console.log("ajax request...");
} else {
$("#username-error").html("invalid email address");
}
}

jquery compare two fields values

hi i have a sign up form , it has six input fields
html code
<div id="signup">
<form id="suform" method="POST" action="signup/newUser">
<p>
<label>Frist Name</label>
<input type="text" name="fName"/>
<span class="errorMessage"></span>
</p>
<p>
<label>Last Name</label>
<input type="text" name="lName"/>
<span class="errorMessage"></span>
</p>
<p>
<label>Email</label>
<input type="text" name="Email"/>
<span class="errorMessage"></span>
</p>
<p>
<label>Mobile Number</label>
<input type="text" name="MNumber"/>
<span class="errorMessage"></span>
</p>
<p>
<label>Password</label>
<input type="password" name="Password"/>
<span class="errorMessage"></span>
</p>
<p>
<label>Re Password</label>
<input type="password" name="RePassword"/>
<span class="errorMessage"></span>
</p>
<p>
<input type="submit" class="button" value="sign up"/>
</p>
</form>
</div>
when the user clicked sign up button , first i ensure that no input fields is empty , if i found any input fields in empty then i print an error message left to that input field ,
jquery code
$(document).ready(function(){
$('#suform').on('submit', function(e){
e.preventDefault();
var errorCount = 0;
$('span.errorMessage').text(''); // reset all error mesaage
$('input').each(function(){
var $this = $(this);
if($this.val() === ''){
var error = 'Please fill ' + $this.prev('label').text(); // take the input field from label
$this.next('span').text(error);
errorCount = errorCount + 1;
}
});
if(errorCount === 0){
$(this)[0].submit(); // submit form if no error
}
});
});
i want the user to input his password twice to ensure that he saves it
my question is how to check the two passwords input fields if they are equal or not , and if not i want to print a message error to the left of that two input fields
code
Checking the fields and showing an error without jQuery:
if (document.forms[0].Password.value != document.forms[0].RePassword.value) {
document.forms[0].Password.parentNode.getElementsByClassName("errorMessage")[0].innerHTML="Passwords aren't the same!";
document.forms[0].RePassword.parentNode.getElementsByClassName("errorMessage")[0].innerHTML="Passwords aren't the same!";
}
If there is more than one form on the page (even just a search form) you'll need to adjust document.forms[0] accordingly.
To use this code in your form, add onsubmit="return checkForm();" to the form tag, like:
<form id="suform" method="POST" action="signup/newUser" onsubmit="return checkForm();">
Then, in your script tag, create the function checkCode which will return false (in other words stop form submission) if there's a problem:
<script type="text/javascript">
<!--
function checkCode() {
if (document.forms[0].Password.value != document.forms[0].RePassword.value) {
document.forms[0].Password.parentNode.getElementsByClassName("errorMessage")[0].innerHTML="Passwords aren't the same!";
document.forms[0].RePassword.parentNode.getElementsByClassName("errorMessage")[0].innerHTML="Passwords aren't the same!";
return false;
}
}
//-->
</script>
Well this might work i suppose.,
var password= $('input[name="Password"]').val();
var repass= $('input[name="RePassword"]').val();
if(password!=repass){
var error = 'Password not matching';
$('input[name="RePassword"]').next('span').text(error);
$('input[name="Password"]').next('span').text(error);
errorCount = errorCount + 1;
}else if(password=="" || repass==""){
if(password==""){
var error = 'Please enter a password.';
$('input[name="Password"]').next('span').text(error)
errorCount = errorCount + 1;
}else{
var error = 'Please enter a repassword.';
$('input[name="RePassword"]').next('span').text(error)
errorCount = errorCount + 1;
}
}
}else{
continue;
}
You can do it like that:
var pass1 = $('input[name=Password]').val();
var pass2 = $('input[name=RePassword]').val();
if(pass1 != '' && pass1 != pass2) {
//show error
var error = 'Password confirmation doesn\'t match.';
$('input[name=Password]').next('span').text(error);
$('input[name=RePassword]').next('span').text(error);
errorCount = errorCount + 1;
}
The "for" property in the label is used as follows:
<label for="myPasswordField">
<input type="password" id="myPasswordField" name="Password" />
</label>
So when you click on the label this will set the focus on the related element with that ID attribute.
To check if the phone field is a number you need that:
var mobile = $('input[name=MNumber]').val();
if(isNaN(parseFloat(mobile )) && !isFinite(mobile )) {
var error = 'Mobile number incorect.';
$('input[name=MNumber]').next('span').text(error);
errorCount = errorCount + 1;
}
<p>
<label>Password</label>
<input type="password" name="Password"/>
<span class="errorMessage"></span>
</p>
<p>
<label>Re Password</label>
<input type="password" name="RePassword"/>
<span class="errorMessage"></span>
</p>
if ( $("input[type=password][name='Password']").val() == $("input[type=text][name='RePassword']").val(){
//Do this
}
Something like this? http://jsfiddle.net/K5CMC/
var $this = $(this);
if($this.val() === ''){
var error = 'Please fill ' + $this.prev('label').text(); // take the input field from label
$this.next('span').text(error);
errorCount = errorCount + 1;
}else if($this.attr('id') === 'Password'){
//compare the two fields
if($('#Password').val() !== $('#RePassword')){
//they don't match, do stuff
}
}
You can do it like this Demo on JsFiddle
$(document).ready(function(){
$('#suform').on('submit', function(e){
e.preventDefault();
var errorCount = 0;
$('span.errorMessage').text(''); // reset all error mesaage
$('input').each(function(){
var $this = $(this);
if($this.val() === ''){
var error = 'Please fill ' + $this.prev('label').text(); // take the input field from label
$this.next('span').text(error);
errorCount = errorCount + 1;
}
else
if($(this).attr('name') == "RePassword")
if($('input[name=Password]').val() != $(this).val())
alert("must have same password");
});
if(errorCount === 0){
$(this)[0].submit(); // submit form if no error
}
});
});​
$(document).ready(function(){
$('#suform').on('submit', function(e){
e.preventDefault();
var errorCount = 0;
$('span.errorMessage').text(''); // reset all error mesaage
$('input').each(function(){
var $this = $(this);
if($this.val() === ''){
var error = 'Please fill ' + $this.prev('label').text(); // take the input field from label
$this.next('span').text(error);
errorCount = errorCount + 1;
}
});
if($('input[name="Password"]').val() != $('input[name="RePassword"]').val())
{
var error = 'Password not match'; // take the input field from label
$('input[name="RePassword"]').next('span').text(error);
errorCount = errorCount + 1;
}
if(errorCount === 0){
$(this)[0].submit(); // submit form if no error
}
});
});

Can validate an array of date[] but not process it?

I have a problem with this now, on the end of my mydate I have put [] so I can have an array to process and on the other page, I have process.php.
In the process.php, I have
foreach($_POST["mydate"] as $mydate ){
if($mydate != ''){
Date processed...etc etc....
}
If I put the [], it will store it but wont validate and if I dont put [], it will validate but not post?
Any thoughts?
<script type="text/javascript">
function checkdate(input){
var validformat=/^\d{2}\/\d{2}\/\d{4}$/ //Basic check for format validity
var returnval=false
if (!validformat.test(input.value))
alert("Invalid Date Format. Please correct and submit again.")
else{ //Detailed check for valid date ranges
var monthfield=input.value.split("/")[0]
var dayfield=input.value.split("/")[1]
var yearfield=input.value.split("/")[2]
var dayobj = new Date(yearfield, monthfield-1, dayfield)
if ((dayobj.getMonth()+1!=monthfield)||(dayobj.getDate()!=dayfield)||(dayobj.getFullYear()!=yearfield))
alert("Invalid Day, Month, or Year range detected. Please correct and submit again.")
else
returnval=true
}
if (returnval==false) input.select()
return returnval
}
function CheckDates(inputs)
{
var i, len;
if (inputs.length) {
len = inputs.length;
for (i = 0; i < len; i++) {
if (!checkdate(inputs[i])) return false;
}
return true;
}
return checkdate(inputs);
}
function add(tbl1) {
var tbl = document.getElementById(tbl1);
var rowCount = tbl.rows.length;
var row = tbl.insertRow(rowCount);
var colCount = tbl.rows[1].cells.length;
for(var i=0; i<colCount; i++) {
var newCell = row.insertCell(i);
newCell.innerHTML = tbl.rows[1].cells[i].innerHTML;
}
}
</script>
<form name "enter" action="enter.php" onSubmit="return Checkdate(this.mydate)" method="post">
<table id="day" border="1">
<tr><b>Valid date format:</b><br></tr>
<tr><td>
<input type="text" name="mydate" />
</table><br>
<input type="submit" value="submit" />
<input type="button" value="Add Row" onclick="add('day')"/>
</form>
EDITTED
removed the space but still doesnt work
If there are more than one of the input field, the name must be mydate[] so they are placed in an array, and in your processing code you have an extra space... $_POST['mydate '] won't work it must be $_POST['mydate']
edit: this line <input type="text" name="mydate" /> must be <input type="text" name="mydate[]" />
Try this construction:
foreach ($_POST["mydate"] as $mydate ) {
if(!empty($mydate) && !is_null($mydate)) {
}
}

Page refreshes on submit click with ajax

I have a small commenting system that I have modified and try implement into the site. It's in 'ajax'. When the jQuery with HTML is embedded into the page the commenting system works fine - i.e. when the user clicks on a submit button the code returns 'false', stops the page from refreshing and submits data. BUT when I implemented the code within my site and placed it in a seperate .js file the code for some reason doesn't work properly. I mean - the page after the onclick refreshes. Why is that so ? The code is not changed at all - when on its own, it works but not in the index.php site when implemented. I tried to change input type to 'button' and call a function from onclick - the page doesn't refresh but also doesn't insert the input..I'm running out of ideas as to why it is that so. Here's the code:
$(document).ready(function () {
$(".submit").click(function () {
var name = $("#name").val();
var email = $("#email").val();
var comment_area = $("#comment_area").val();
var dataString = 'name=' + name + '&email=' + email + '&comment_area=' + comment_area;
var emailReg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
var emailaddressVal = $("#email").val();
if (name == '' || !emailReg.test(emailaddressVal) || comment == '') {
alert('Please enter valid data and type in message'); return false;
}
else {
$.ajax({
type: "POST",
url: "comments.php",
data: dataString,
cache: false,
success: function (html) {
$("#com_list").append(html);
$("#com_list").fadeIn("slow");
$("#flash").fadeOut('fast');
}
});
} return false;
});
});
//END
//COM LIST
//HTML / PHP
<div class="slider">
<form id="comment_form" name="comment_form" method="post" action="#"
enctype="multipart/form-data">
<input type="text" id="name" name="name" maxlength="16"/> Name<br /><br/>
<input type="text" id="email" name="email"/> Email (will not show)<br /><br/>
<textarea id="comment_area" name="comment_area" maxlength="1000"></textarea><br /><br/>
<input type="submit" class="submit" name="submit_comment" value="submit"/> &
nbsp;comment or <a href="index.php" id="cancel"
onmousedown="$('.slider').hide();$('#com_list').show();"><u>cancel</u></a>
</form>
</div>
//comments.php
if($_POST) {
$name=$_POST['name'];
$email=$_POST['email'];
$comment_area=$_POST['comment_area'];
//$lowercase = strtolower($email);
//$image = md5( $lowercase );
$insert = mysqli_query($connect,"INSERT INTO comments (name,email,comment,com_date)
VALUES ('$name','$email','$comment_area',curdate())");
}
////////////////
Thanks for any suggestions..
aha!
there is an error in your js:
in my console i'm getting "comment is not defined "
if(name=='' || !emailReg.test(emailaddressVal) || comment=='')
and earlier you have:
var comment_area = $("#comment_area").val(); //<--
change this to comment and it'll get past that at least.
EDIT: a little background. when firefox hits an error, sometimes it'll swallow it, and just stop running any javascript after that error, so your return false and or prevent default code isn't fire, so it's still going to post the form and refresh the page.
Change this line:
$(".submit").click(function () {
To this:
$("#comment_form").submit(function () {
The submit event gets triggered on the <form> element, not on the submit button.
Keep your damn code clean, so you can understand what you are cooking...
This will work for you:
$(document).ready(function(){
$("#comment_form").submit(function(e){
e.preventDefault(); // stop refresh
var name = $("#name").val();
var email = $("#email").val();
var comment_area = $("#comment_area").val();
var dataString = 'name='+ name + '&email=' + email + '&comment_area=' + comment_area+'&submit_comment=true';
var emailReg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
var emailaddressVal = $("#email").val();
if(name=='' || !emailReg.test(emailaddressVal) || comment==''){
alert('Please enter valid data and type in message');
} else{
$.ajax({
type: "POST",
url: "comments.php",
data: dataString,
cache: false,
success: function(html){
$("#com_list").append(html);
$("#com_list").fadeIn("slow");
$("#flash").fadeOut('fast');
}
});
}
});
$('#cancel').click(function(e){
e.preventDefault();
$('.slider').hide();
$('#com_list').show();
});
});
Here is some more clean code...
<div class="slider">
<form id="comment_form" name="comment_form" method="post" action="#" enctype="multipart/form-data">
<input type="text" id="name" name="name" maxlength="16"/> Name<br /><br/>
<input type="text" id="email" name="email"/> Email (will not show)<br /><br/>
<textarea id="comment_area" name="comment_area" maxlength="1000"></textarea><br /><br/>
<input type="submit" class="submit" name="submit_comment" value="submit"/> comment or <u>cancel</u>
</form>
</div>
Here is some other clean and SECURE code
<?php
if(isset($_POST['submit_comment'])){
$name = mysql_real_escape_string($_POST['name']);
$email = mysql_real_escape_string($_POST['email']);
$comment_area = mysql_real_escape_string($_POST['comment_area']);
//$lowercase = strtolower($email);
//$image = md5( $lowercase );
$query = 'INSERT INTO comments (name,email,comment,com_date) '.
"VALUES ('$name','$email','$comment_area',CURDATE())";
$insert = mysqli_query($connect, $query);
}
?>

Categories