Form validation using Jquery plugin and additional methods - javascript

I want to use the jquery plugin for validating my form with letters only in name section. such that when a user enters special characters or numbers it gives an error. Also i want to check the form validation as the users types the information i.e. realtime validation before submitting the form.
//jquery validation
// Wait for the DOM to be ready
$(function() {
// Initialize form validation on the registration form.
// It has the name attribute "registration"
$("form[name='book']").validate({
// Specify validation rules
rules: {
// The key name on the left side is the name attribute
// of an input field. Validation rules are defined
// on the right side
fname: {
required: true,
lettersonly: true
},
lname:{
required: true,
lettersonly: true
},
email: {
required: true,
// Specify that email should be validated
// by the built-in "email" rule
email: true
},
// Specify validation error messages
messages: {
fname: {
required:"Please enter your firstname",
lettersonly:"Letters allowed only"
},
lname: {
required:"Please enter your firstname",
lettersonly:"Letters allowed only"
},
email: "Please enter a valid email address"
},
// Make sure the form is submitted to the destination defined
// in the "action" attribute of the form when valid
submitHandler: function(form) {
form.submit();
}
});
});
<script src="design/bootstrap-3.3.7-dist/js/jquery.validate.js"></script>
<script src="design/bootstrap-3.3.7-dist/js/additional-methods.js"></script>
<form name="book" id="book" action="" method="post">
<div class="row form-group">
<div class="col-md-6 ">
<label class="" for="fname">First Name</label>
<input type="text" name="fname" id="fname" class="form-control" placeholder="First Name">
</div>
<div class="col-md-6">
<label class="" for="lname">Last Name</label>
<input type="text" name="lname" id="lname" class="form-control" placeholder="Last Name">
</div>
</div>
<div class="row form-group">
<div class="col-md-6 ">
<label class="" for="date">Date</label>
<input type="text" id="date" class="form-control datepicker px-2" placeholder="Date of visit">
</div>
<div class="col-md-6">
<label class="" for="email">Email</label>
<input type="email" name="email" id="email" class="form-control" placeholder="Email">
</div>
</div>
<div class="row form-group">
<div class="col-md-12">
<label class="" for="treatment">Service You Want</label>
<select name="treatment" id="treatment" class="form-control">
<option value="">Hair Cut</option>
<option value="">Hair Coloring</option>
<option value="">Perms and Curls</option>
<option value="">Hair Conditioning</option>
<option value="">Manicure</option>
<option value="">Pedicure</option>
<option value="">Nails Extension</option>
<option value="">Nail Design</option>
<option value="">Waxing Eyebrows</option>
<option value="">Waxing Hands/Legs</option>
<option value="">Full Face Waxing</option>
<option value="">Full Body/Body Parts Wax</option>
</select>
</div>
</div>
<div class="row form-group">
<div class="col-md-12">
<label class="" for="note">Notes</label>
<textarea name="note" id="note" cols="30" rows="5" class="form-control" placeholder="Write your notes or questions here..."></textarea>
</div>
</div>
<div class="row form-group">
<div class="col-md-12">
<center><input type="submit" value="Book Now" class="btn btn-primary btn-lg"></center>
</div>
</div>
</form>
I want to use the jquery plugin for validating my form with letters only in name section. such that when a user enters special characters or numbers it gives an error

var RegEx = /^[a-zA-Z\s]*$/;
if (RegEx.test($('#input').val())) {
}
else {
$('#input').val("");
}
});​````
You have to wrap all the input elements in <form></form> and use jquery Validate plugin. Refer this link: http://jqueryvalidation.org/validate/ for detailed explanation

How about doing something like this?
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
<form id="form">
<label for="name">Name: </label>
<input type="text" name="name">
<div id="error"></div>
</form>
<script>
;(function($){
$.fn.extend({
donetyping: function(callback,timeout){
timeout = timeout || 1e3; // 1 second default timeout
var timeoutReference,
doneTyping = function(el){
if (!timeoutReference) return;
timeoutReference = null;
callback.call(el);
};
return this.each(function(i,el){
var $el = $(el);
// Chrome Fix (Use keyup over keypress to detect backspace)
// thank you #palerdot
$el.is(':input') && $el.on('keyup keypress paste',function(e){
// This catches the backspace button in chrome, but also prevents
// the event from triggering too preemptively. Without this line,
// using tab/shift+tab will make the focused element fire the callback.
if (e.type=='keyup' && e.keyCode!=8) return;
// Check if timeout has been set. If it has, "reset" the clock and
// start over again.
if (timeoutReference) clearTimeout(timeoutReference);
timeoutReference = setTimeout(function(){
// if we made it here, our timeout has elapsed. Fire the
// callback
doneTyping(el);
}, timeout);
}).on('blur',function(){
// If we can, fire the event since we're leaving the field
doneTyping(el);
});
});
}
});
})(jQuery);
function validate(value) {
var regex = /\d/g;
if (regex.test(value)) {
$('#error').text('Only text allowed!');
} else {
$('#error').empty();
}
}
$('input[name=name]').donetyping(function(e){
validate($(this).val());
});
</script>
</body>
</html>
Credits to this https://stackoverflow.com/a/14042239/9379378

//jquery validation booking page
// Wait for the DOM to be ready
$(function() {
// Initialize form validation on the registration form.
// It has the name attribute "registration"
$("form[name='book']").validate({
//on key up validation
onkeyup: function(element) {
$(element).valid();
},
// Specify validation rules
rules: {
// The key name on the left side is the name attribute
// of an input field. Validation rules are defined
// on the right side
fname: {
required: true,
lettersonly: true
},
lname:{
required: true,
lettersonly: true
},
email: {
required: true,
// Specify that email should be validated
// by the built-in "email" rule
email: true
},
password: {
required: true,
minlength: 5
}
},
// Specify validation error messages
messages: {
fname: {
required:"Please enter your firstname",
lettersonly:"Letters allowed only"
},
lname: {
required:"Please enter your lastname",
lettersonly:"Letters allowed only"
},
email: "Please enter a valid email address"
},
// Make sure the form is submitted to the destination defined
// in the "action" attribute of the form when valid
submitHandler: function(form) {
form.submit();
}
});
});

Related

jQuery validate plugin working only on last shown div [duplicate]

This question already exists:
jQuery show/hide form with jQuery validate plugin working on last shown div only
Closed 4 years ago.
I am trying to validate my form that is a jQuery show/hide form. jQuery validate plugin only validates my last input on the last div (input type file). I can currently upload an image and submit the form successfully with the remaining inputs empty.
Below is the third div and when i click post ad with no inputs filled in, "This field is required" is shown.
Below is the first div with no validation messages
Below is the second div with no validation messages
Here is my form:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Zootopia</title>
<script src="http://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/jquery.validate.min.js"></script>
</head>
<body>
<form id="ad_form" method="post">
<div id="ad_form_section1">
<div class="form-group">
<label for="ad_title">Ad Title</label>
<input type="text" class="form-control stored" id="ad_title" placeholder="e.g. German Sheperd puppy - 4 months old" name="ad_title" required>
</div>
<div class="form-group">
<label for="description">Describe what you're offering</label>
<textarea class="form-control stored" id="description" rows="6" placeholder="e.g. Owner supervised visits, minimum 1hr bookings, play with my german sheperd puppy in my backyard" name="description" required></textarea>
</div>
<button type="button" id="ad_section2" class="btn btn-primary"> Next </button>
</div>
<div id="ad_form_section2">
<div class="form-group">
<label for="location"> Location</label>
<input type="text" id="location_ad" class="form-control stored" placeholder="location" name="location" required/>
</div>
<div class="form-group">
<label for="price">Price</label>
<input type="text" id="price" class="form-control stored" name="price" placeholder="$0.00" required/>
</div>
<button type="button" id="back_section1" class="btn btn-primary"> Back </button>
<button type="button" id="ad_section3" class="btn btn-primary"> Next </button>
</div>
<div id="ad_form_section3">
<div>
<label> Select pet pictures</label>
<input type="file" name="multiple_files[]" id="multiple_files" multiple required/>
</div>
<button type="button" id="back_section2" class="btn btn-primary"> Back </button>
<input type="hidden" name="action_type" value="add" />
<input type="submit" id="ad_button" class="btn btn-primary" value="Post ad" />
</div>
</form>
Here is my JavaScript:
$(document).ready(function(){
$("#ad_section2").click(function(){
$("#ad_form_section1").hide();
$("#ad_form_section2").show();
});
$("#back_section1").click(function(){
$("#ad_form_section1").show();
$("#ad_form_section2").hide();
});
$("#ad_section3").click(function(){
$("#ad_form_section3").show();
$("#ad_form_section2").hide();
});
$("#back_section2").click(function(){
$("#ad_form_section2").show();
$("#ad_form_section3").hide();
});
$("#ad_form").validate({
rules:{
ad_title:{
required: true
},
description:{
required: true
},
location:{
required: true
}
},
messages:{
ad_title: {
required: "please enter an ad title"
},
description: {
required: "please enter a description"
},
location: {
required: "please enter a location"
}
},
submitHandler: function(form) {
var petID = $( "#pet_ad option:selected" ).val();
var addAdUrl = "../../controller/post_ad_process.php?petID=" + petID;
$(form).ajaxSubmit({
url:addAdUrl,
type:"post",
datatype: 'json',
success: function(result){
if(result.petAd == false){
alert("Pet ad already exists!");
}else{
alert("Ad posted!");
$('#image_table').hide();
}
},
error: function(error) {
alert("Error");
}
});
}
});
})
Here is my CSS:
#ad_form_section2,
#ad_form_section3{
display: none;
}
You need to add a condition before you show/hide next fields
if ( $('field-id').valid() ) {
// Code
}
For example:
$("#ad_section2").click(function(){
if ($('#ad_title').valid() && $('#description').valid()) {
$("#ad_form_section1").hide();
$("#ad_form_section2").show();
}
});
Also, don't forget to set character encoding to avoid characters range error, Add the following code just below <head> tag:
<meta charset="UTF-8">
Form Example:
$(document).ready(function(){
$("#ad_form").validate({
rules:{
ad_title:{
required: true,
minlength: 3, // set minimum title length
},
description:{
required: true,
minlength: 10,
},
location:{
required: true
}
},
messages:{
ad_title: {
required: "please enter an ad title",
minlength: "Your title must be more than 3 characters!",
},
description: {
required: "please enter a description",
minlength: "Your description must be at least 10 characters long",
},
location: {
required: "please enter a location"
}
},
submitHandler: function(form) {
var petID = $( "#pet_ad option:selected" ).val();
var addAdUrl = "../../controller/post_ad_process.php?petID=" + petID;
$(form).ajaxSubmit({
url:addAdUrl,
type:"post",
datatype: 'json',
success: function(result){
if(result.petAd == false){
alert("Pet ad already exists!");
}else{
alert("Ad posted!");
$('#image_table').hide();
}
},
error: function(error) {
alert("Error");
}
});
}
});
$("#ad_section2").click(function(){
// Check if valid before show/hide
if ($('#ad_title').valid() && $('#description').valid()) {
$("#ad_form_section1").hide();
$("#ad_form_section2").show();
}
});
$("#back_section1").click(function(){
$("#ad_form_section1").show();
$("#ad_form_section2").hide();
});
$("#ad_section3").click(function(){
// Check if valid before show/hide
if ($('#location_ad').valid()) {
$("#ad_form_section3").show();
$("#ad_form_section2").hide();
}
});
$("#back_section2").click(function(){
$("#ad_form_section2").show();
$("#ad_form_section3").hide();
});
});
#ad_form_section2,
#ad_form_section3 {
display: none;
}
label.error {
color: red;
}
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/jquery.validate.min.js"></script>
<div class="container">
<form id="ad_form" method="post">
<div id="ad_form_section1">
<div class="form-group">
<label for="ad_title">Ad Title</label>
<input type="text" class="form-control stored" id="ad_title" placeholder="e.g. German Sheperd puppy - 4 months old" name="ad_title">
</div>
<div class="form-group">
<label for="description">Describe what you're offering</label>
<textarea class="form-control stored" id="description" rows="6" placeholder="e.g. Owner supervised visits, minimum 1hr bookings, play with my german sheperd puppy in my backyard" name="description" required></textarea>
</div>
<button type="button" id="ad_section2" class="btn btn-primary"> Next </button>
</div>
<div id="ad_form_section2">
<div class="form-group">
<label for="location"> Location</label>
<input type="text" id="location_ad" class="form-control stored" placeholder="location" name="location" required/>
</div>
<div class="form-group">
<label for="price">Price</label>
<input type="text" id="price" class="form-control stored" name="price" placeholder="$0.00" required/>
</div>
<button type="button" id="back_section1" class="btn btn-primary"> Back </button>
<button type="button" id="ad_section3" class="btn btn-primary"> Next </button>
</div>
<div id="ad_form_section3">
<div>
<label> Select pet pictures</label>
<input type="file" name="multiple_files[]" id="multiple_files" multiple required/>
</div>
<button type="button" id="back_section2" class="btn btn-primary"> Back </button>
<input type="hidden" name="action_type" value="add" />
<input type="submit" id="ad_button" class="btn btn-primary" value="Post ad" />
</div>
</form>
</div>
More examples from documentation
By default the plugin is going to ignore any/all fields that are hidden. You have to set to the ignore option to "nothing".
$("#ad_form").validate({
ignore: [], // ignore nothing, validate everything
rules:{
ad_title:{ ....
If you're expecting validation when you show/hide sections of the form, that's not how it works. You're going to have to programmatically trigger validation on the relevant fields as you click back and forth. Use the .valid() method for this.
However, multi-step validation can quickly get tedious so you may have to re-think your entire approach. I personally like to enclose each section within its own set of <form></form> tags so I can control validation on each step separately.
Here's one example:
https://stackoverflow.com/a/20481497/594235

enable submit button when jquery.validate has valiated the form

I have a form that is being validated using jquery.validate.
I have added in reCAPTCHA 2.0 and this is being validated also.
However I want the form's submit button to be disabled untill the form is valid and this is where I am stuck.
The button is disabled but is not being enabled after the entries and captcha are all validated.
This is my form code
<div class="contact-Form">
<form id="form">
<label for="name">Name</label><br>
<input name="firstname" type="text" id="firstname" class="inputbox" value="" placeholder="Your name...">
<br><br>
<label for="name">Email</label><br>
<input name="email" type="email" id="email" class="inputbox" value="" placeholder="Your email address...">
<br><br>
<label for="name">Message</label><br>
<textarea class="messagebox" rows="10" cols="20" name="message" id="message" value="" placeholder="Your message..."></textarea>
<br><br>
<input type="hidden" class="hiddenRecaptcha required" name="hiddenRecaptcha" id="hiddenRecaptcha">
<div class="g-recaptcha" data-sitekey="6LcjETAUAAAAAPC7-qXZW4xI89k1EhUzPWnD5mAP" data-callback="recaptchaCallback"></div>
<input type="hidden" class="hiddenRecaptcha required" name="hiddenRecaptcha" id="hiddenRecaptcha">
<br><br>
<button id="submit" disabled="disabled" type="submit">Submit</button>
</form>
</div>
And my javascript
$().ready(function() {
$("#form").validate({
ignore: ".ignore",
rules: {
"firstname": {
required: true,
minlength: 3
},
"email": {
required: true,
email: true
},
"message": {
required: true
},
"hiddenRecaptcha": {
required: function() {
if(grecaptcha.getResponse() == '') {
return true;
} else {
return false;
}
}
}
},
messages: {
"firstname": {
required: "<br/> You have not entered a name!",
minlength: "<br/> Your name must consist of atleast 3 characters",
},
"email": {
required: "<br/> You have not entered an email address!",
email: "<br/> Please use a valid email address!",
},
"message": {
required: "<br/> You have not entered a message!",
}
}
});
$('#form input').on('keyup blur click', function () { // fires on every keyup & blur
if ($('#form').valid()) { // checks form for validity
$('button.btn').prop('disabled', false); // enables button
} else {
$('button.btn').prop('disabled', 'disabled'); // disables button
}
});
});
function recaptchaCallback() {
$('#hiddenRecaptcha').valid();
};
Edit
I have changed this function
$('#form input').on('keyup blur click', function () { // fires on every keyup & blur
if ($('#form').valid()) { // checks form for validity
$('button.btn').prop('disabled', false); // enables button
} else {
$('button.btn').prop('disabled', 'disabled'); // disables button
}
});
To this
$('#form input').bind('keyup blur click', function () {
if ($(this).validate().checkForm()) {
$('#submit').removeClass('button_disabled').attr('disabled', false); // enables button
} else {
$('#submit').addClass('button_disabled').attr('disabled', true); // disables button
}
});
It now enables the button when any input is valid. I want it to only enable the button when all inputs are valid.
Can someone point out where I am going wrong please I have checked other posts which is how I managed to get this working up till this point
You can try by removing the disabled attribute from your input btn
example:
$("button.btn").removeAttr("disabled");
Hope this helps you.

Jquery Validate Form issue while split by 2 screen

I'm using the JQuery validate for my contact form. It was a single page form. But right now its split by 2 set. First set has few fields with a continue button. Then second set will be given by continue button. The continue btn validating without an issue. But it doesn't give the alert like the final submit btn.
Can you help me to resolve this
My Markup
<form name="contact" id="contact" method="post" action="http://action.com">
<div id="form-fields">
<!-- Form Step One -->
<div id="form_step1">
<div class="form-row">
<label class="request_label">Program of Interest</label>
<select id="CurriculumID" name="CurriculumID">
<option selected="selected" value="">What program would you like to study</option>
</select>
<br />
</div>
<div class="form-row">
<label class="request_label">First Name</label>
<input name="firstname" id="firstname" type="text" title="First Name" />
<br />
</div>
<div class="form-row">
<label class="request_label">Last Name</label>
<input name="lastname" id="lastname" type="text" title="Last Name" />
<br />
</div>
<!-- CLOSING (FIRST NAME AND LAST NAME) -->
<div class="req_btn_wrapper">
<a href="javascript:void(0)" id="next">
<img src="images/next_btn.png">
</a>
</div>
</div>
<!-- Form Step Two -->
<div id="form_step2">
<div class="form-row">
<label class="request_label">Email</label>
<input name="email" id="email" type="text" title="Email" />
<br />
</div>
<div class="form-row">
<div class="split-form-row">
<label class="request_label">Phone</label>
<input name="dayphone" id="dayphone" class="form_phone" type="text" onkeypress="return numbersonly(this, event)" title="Phone" />
<br />
</div>
<div class="split-form-row">
<label class="request_label">Zip Code</label>
<input name="zip" id="zip" class="form_zip" type="text" title="Zip Code" />
<br />
</div>
<div id="cityStateInput">
<input name="city" id="city" type="text" title="City" placeholder="City" />
<br />
<select name="state" id="state">
<option selected="selected" value="">Select a State:</option>
<option value="N/A">Orange</option>
<option value="N/A">lorem</option>
</select>
<br />
</div>
</div>
<div class="form-row">
<label class="request_label">Year</label>
<select name="gradyear" id="gradyear">
<option selected="selected" value="">Please Select</option>
<option value="2017">2017</option>
<option value="2016">2016</option>
<option value="2015">2015</option>
<option value="2014">2014</option>
</select>
</div>
<!-- Radio -->
<div class="radio_row">
<p id="military" class="military_label">Are you working in the military?</p>
<div class="radio_option">
<input type="radio" name="verify" value="Yes"><span id="yes1" for="yes">Yes</span>
</div>
<div class="radio_option">
<input type="radio" name="verify" value="No" checked="checked"><span id="no1">No</span>
</div>
</div>
<!-- Radio -->
<div class="clear"></div>
<!-- CLOSING CLEAR -->
<div class="req_btn_wrapper">
<input name="submit" id="submit" type="image" src="images/btn_submit_request.png" value="" />
</div>
</div>
</form>
My Js script
// Validate signup form on keyup and submit
$("#contact").validate({
ignore: ":hidden",
onclick: false,
onfocusout: false,
onsubmit: true,
onkeyup: false,
onkeydown: false,
rules: {
// Insert fields from the form
email: {
email: true
},
zip: {
minlength: 5,
required: true,
checkLabel: true,
zipUS: true
},
city: {
checkLabel: true,
required: true
},
dayphone: {
required: true,
checkPhoneValue: true
},
state: {
required: true
},
firstname: {
required: true,
checkLabel: true
},
lastname: {
required: true,
checkLabel: true
},
},
messages: {
// Place custom error messages
CurriculumID: "Please select a program.",
firstname: "Please enter your first name.",
lastname: "Please enter your last name.",
dayphone: "Please enter a valid phone number.",
email: "Please enter a valid email address.",
zip: "Please enter a valid Zip code.",
gradyear: "Please select H.S. graduation year.",
city: "Please enter your city.",
state: "Please select your state."
},
// Error placement
showErrors: function(errorMap, errorList) {
try {
if (submitted) {
var summary = "Please fix the following: \n\n";
$.each(errorList, function() {
summary += " - " + this.message + "\n";
});
alert(summary);
submitted = false;
}
//this.defaultShowErrors();
} catch (err) {
Raven.captureException(err);
}
},
invalidHandler: function(form, validator) {
try {
submitted = true;
} catch (err) {
Raven.captureException(err);
}
}
}); // END FORM VALIDATION
$(document).ready(function() {
$('#form_step2').hide();
var validateStep1 = function() {
var isValid_1 = $('#CurriculumID').valid();
var isValid_2 = $('#firstname').valid();
var isValid_3 = $('#lastname').valid();
if (isValid_1 && isValid_2 && isValid_3) {
$('#form_step1').hide();
$('#form_step2').show();
return false;
}
}
// Show step 2
$('#next').click(function() {
validateStep1();
});
$('#back-button').click(function() {
$('#form_step1').show();
$('#form_step2').hide();
});
// Check input value against inline label
jQuery.validator.addMethod("checkLabel", function(value, element) {
return this.optional(element) || value != element.title;
}, "Please enter a value.");
})
You have a couple issues that could break the expected behavior of the jQuery Validate plugin...
$("#contact").validate({
ignore: ":hidden",
onclick: false,
onfocusout: false,
onsubmit: true, // <- NEVER set to 'true'
onkeyup: false,
onkeydown: false, // <- No such thing
....
There is absolutely no such thing called onkeydown. Please refer to the documentation for all available options.
The onsubmit option must never be set to true as this breaks the built-in onsubmit function. This option can only be set to false or an over-riding function. If you want to keep the default submit functionality un-altered, then you must remove the onsubmit option from your .validate() method.
See: jqueryvalidation.org/validate/#onsubmit
"Set to false to use only other events for validation.
Set to a Function to decide for yourself when to run validation.
A boolean true is not a valid value".
The continue btn validating without an issue. But it doesn't give the alert like the final submit btn.
As far as your issue, you need to look at your JavaScript error console.
ReferenceError: Can't find variable: submitted
I removed the if (submitted) conditional within showErrors and got your "next" button working...
DEMO: http://jsfiddle.net/vpgmnLg0/

How to validate form fields and post the form data to server using JQuery and Ajax?

I am trying to validate form fields like, Name (must not be blank), Email_id(must be valid), Mobile(Must be valid). After the filling the all info I have to send this information to server, and redirect response to different page. Here nothing is working,
my form.html
<form class="form-horizontal" id="scheduleLaterForm" name="scheduleLaterForm">
<div class="col-lg-8">
<div class="fieldgroup">
<label class="col-lg-3 control-label" for="userName">Name:<font
style="color: red;">*</font></label>
<div class="col-lg-9">
<input style=" height: 30px;" class="form-control" id="userName" name="userName"
placeholder="Full Name" value="" type="text" required>
</div>
</div>
<div class="fieldgroup">
<label for="email" class="col-lg-3 control-label">Email:<font
style="color: red;">*</font></label>
<div class="col-lg-9">
<input style="height: 30px;" class="form-control" name="email"
id="email" placeholder="you#example.com" value=""
type="text" required>
</div>
</div>
<div class="fieldgroup">
<label for="userContactNumber" class="col-lg-3 control-label">Mobile:<font
style="color: red;">*</font></label>
<div class="col-lg-9">
<input style="height: 30px; width:100%;" class="form-control" id="userContactNumber"
name="userContactNumber" placeholder="Mobile Number"
onkeypress="enableKeys(event);" maxlength="10" type="text" required>
</div>
</div>
<div class="fieldgroup">
<label class="col-lg-3 control-label"></label>
<div class="col-lg-7">
<input type="submit" value="Register" id="btnBooking" class="submit">
</div>
</div>
</div>
</form>
script for validating form and sending data
<script>
$(document).ready(function(){
$("#scheduleLaterForm").validate({
rules: {
userName: "required",
email: {
required: true,
email: true
},
userContactNumber: "required"
},
messages: {
userName: "Please enter your Name",
userContactNumber: "Please enter your Mobile number",
email: "Please enter a valid email address",
},
submitHandler: function(form) {
// get values from textboxs
var uName = $('#userName').val();
var mailId = $('#addressemailId').val();
var mobNum = $('#userContactNumber').val();
$.ajax({
url:"http://localhost/services/bookService4Homes.php",
type:"GET",
dataType:"json",
data:{type:"booking",Name:uName, Email:mailId, Mob_Num:mobNum },
//type: should be same in server code, otherwise code will not run
ContentType:"application/json",
success: function(response){
alert("success");
//alert(JSON.stringify(response));
},
error: function(err){
alert("fail");
//alert(JSON.stringify(err));
}
});
return false; // block regular submit
}
});
});
</script>
Php code
<?php
header('Access-Control-Allow-Origin: *');//Should work in Cross Domaim ajax Calling request
mysql_connect("localhost","root","root");
mysql_select_db("service4homes");
if(isset($_GET['type']))
{
if($_GET['type']=="booking"){
$name = $_GET ['Name'];
$mobile = $_GET ['Mob_Num'];
$mail = $_GET ['Email'];
$query1 = "insert into customer(cust_name, cust_mobile, cust_email) values('$name','$mobile','$mail')";
$result1=mysql_query($query1);
}
}
else{
echo "Invalid format";
}
?>
You do not need an external click handler because the plugin automatically captures the click (of a type="submit") and blocks the submit.
You need an input or button in your form that is type="submit", otherwise the plugin will not be triggered at all.
You cannot have an external .ajax function while you have form.submit within the submitHandler of your .validate() method. This means the plugin is trying to submit the form while your click handler is trying to use ajax. They both cannot work at the same time. As per docs, any ajax belongs inside the submitHandler, and it's "the right place to submit a form via Ajax after it is validated".
You don't need to check form validity because when you use the built in submitHandler, this is also done automatically.
The jQuery4U code is nothing but complicated junk; everything can be simplified greatly. It serves no useful purpose other than to cause more confusion to those seeking guidance. It comes from a popular, yet poorly explained, online demo/tutorial by Sam Deering that is linked to/from many places.
$(document).ready(function(){
$("#register-form").validate({
rules: {
userName: "required",
email: {
required: true,
email: true
},
userContactNumber: "required"
},
messages: {
userName: "Please enter your Name",
userContactNumber: "Please enter your Mobile number",
email: "Please enter a valid email address",
},
submitHandler: function(form) {
// get values from textboxs
var uName = $('#userName').val();
var mailId = $('#addressemailId').val();
var mobNum = $('#userContactNumber').val();
$.ajax({
url:"http://192.168.1.11/services/bookService4Homes.php",
type:"POST",
dataType:"json",
data:{type:"booking",Name:uName, Email:mailId, Mob_Num:mobNum },
//type: should be same in server code, otherwise code will not run
ContentType:"application/json",
success: function(response){
//alert(JSON.stringify(response));
},
error: function(err){
//alert(JSON.stringify(err));
}
});
return false; // block regular submit
}
});
});
DEMO: http://jsfiddle.net/mh6cvf2u/

Multiple validation in javascript/jquery/html form

I am using bootstrap3 form with jquery/javascript to validate input. This was taken from here
Here is part of my form:
<form id="contact-form" action="#" class="form-horizontal">
<fieldset>
<div class="form-group">
<label class="sr-only" for="name">Your Name</label>
<div class="controls">
<input type="text" class="input-xlarge form-control" name="name" id="name" placeholder="Your Name">
</div>
</div>
<div class="form-group">
<label class="sr-only" for="email">Email Address</label>
<div class="controls">
<input type="text" class="input-xlarge form-control" name="email" id="email" placeholder="Email">
Here is the javascript:
<script>
$(document).ready(function(){
jQuery.validator.setDefaults({
errorClass: "help-block"
});
$('#contact-form').validate({
rules: {
name: {
minlength: 3,
regex: "/^[A-Za-z\']*$/",
required: true
},
email: {
required: true,
email: true
},
subject: {
minlength: 2,
required: true
},
message: {
minlength: 2,
maxlength: 400,
required: true
}
},
highlight: function(element) {
$(element).closest('.control-group').removeClass('success').addClass('error');
},
success: function(element) {
element
.text('OK!').addClass('valid')
.closest('.control-group').removeClass('error').addClass('success');
}
});
}); // end document.ready
</script>
The required field and number of digits work wonderfully well. I also intend to add further validation, for example, accept alphabets in name field. I have tried using regex but does not seem to be working.
how to use regex (or multiple) validation in this type of javascript validation ?
how to give appropriate error message when a field has multiple validations (only alphabets and more than 3 characters) ?
I am very new to web development, so these might appear noob questions. Just getting hands on html now. Please guide in right direction.
For email you should add something like this:
$.validator.addMethod("email", function(value, element) {
return this.optional(element) || /^[a-zA-Z0-9._-]+#[a-zA-Z0-9-]+\.[a-zA-Z.]{2,5}$/i.test(value);
}, "Invalid email address");
then rules for email should be:
email: "required email",

Categories