Trouble with validate() on jquery - javascript

I have html like these
<form class="form-filter" id="form-filter-excel" role="form">
<div class="row">
<div class="col-md-4 col-sm-5">
<label>Date range</label>
<div class="input-group input-daterange datepicker">
<input id="fRange" name="fRange" class="form-control input-sm" type="text">
<span class="input-group-addon bg-primary">to</span>
<input id="sRange" name="sRange" class="form-control input-sm" type="text">
</div>
</div>
<div class="col-md-2 col-sm-1">
<label>
</label>
<a class="btn btn-wide btn-primary form-control" href="#" id="btnexport" ><i class="fa fa-file-excel-o"></i> Export To Excel</a>
</div>
</div>
</form>
end here my screen shoot
My question i wanna use validate() on jquery, but i'm kinda stuck i wanna use class= "input-daterange" as field, and the input fRange and sRange as required. How do i did that, if i using fRange and sRange as field, the error massage show up mess. Any idea??
UPDATE :
Sorry for not unclear my question
I'm using jquery validate like these
$('#form-filter-excel').validate({
highlight: function(element) {
$(element).closest('.form-group').prop('required',true);
},
unhighlight: function(element) {
$(element).closest('.form-group').prop('required',false);
},
errorElement: 'span',
errorClass: 'help-block',
errorPlacement: function(error, element) {
if(element.parent('.input-group').length) {
error.insertAfter(element.parent());
} else {
error.insertAfter(element);
}
},
rules: {
fRange: {
required: true,
date: true
},
sRange: {
required: true,
date: true
}
},
messages: {
fRange: "Please insert these input",
sRange: "Please insert these input"
},
});
$('#btnexport').click(function() {
$('#form-filter-excel').valid();
if($('#form-filter-excel').valid()==true)
{
var Fod = $('#fRange').val();
var Tod = $('#sRange').val();
window.open(host+"ajax/excelpoinfo?Fod=" + Fod +"&Tod=" + Fod, '_blank');
}
});
but the problem is the error massage not show under my input but show error like these on my screen
What i need is the error massage show on under each my input.
UPDATE:
I change my mind, i'm using sweet alert then, tq for helping. And for Mayank Pandeyz, u didnt see my question clearly, like i said, that not helping, even u said change replacement. Still not work.

On both the textbox provide the name attribute with its values like:
<form id="frmDetails" name="frmDetails">
<input type="textbox" name="fRange">
<input type="textbox" name="sRange">
</form>
And put the validation code on these like:
$('#frmDetails').validate({
rules:
{
fRange: {
required: true
},
sRange: {
required: true
}
},
messages:
{
fRange: {
required: "Please select fRange"
},
sRange: {
required: "Please select sRange"
}
}
});
Working Fiddle

Related

Form validation using Jquery plugin and additional methods

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();
}
});
});

How to disable submit button after click submit button

I have created forms using php and using jquery for validation.What i exactly need is if validation successful on submit button, disable the submit button till submission gets over.Here is my code:
if(document.location.pathname == "/contact-us"){
$("#form-contact-user").validate({
ignore: [],
rules: {
name:{
required: true
},email: {
email: true
},
phne: {
phnDash: true
},
zip: {
zipcode: true
}
},
errorPlacement: function(error, element) {
if (element.attr("type") == "checkbox") {
error.appendTo( element.parent().parent().parent(".form-checkboxes"));
}
else if (element.attr("name") == "mailing_address")
{
error.appendTo(element.parent().parent().parent());
}
else{
error.insertAfter(element);
}
}
});
Try this:
$('#btnId').attr('disabled', true);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="submit" id="btnId" value="Submit">
I hope this is what you are looking for,
$('#submitBtn').click(function(event) {
//event.preventDefault();
$(this).attr('disabled', true);
//Perform Validation
//if(valid) {
// $("#form-contact-user").submit();
//}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="submit" id="submitBtn" value="Submit">
According to the documentation you can use:
submitHandler (default: native form submit):
Callback for handling the actual submit when the form is valid.
ANSWER UPDATED
From your comment:
Getting the following error:-Uncaught TypeError: Cannot read property 'call' of undefined
This message depends on your rules. Because I don't know anything about your
html I can also assume a possible structure in the following snippet:
$("#form-contact-user").validate({
debug: true,
rules: {
name: {
required: true,
minlength: 2
},
email: {
required: true
},
phone: {
required: true
},
zip: {
required: true
}
},
errorPlacement: function (error, element) {
if (element.attr("type") == "checkbox") {
error.appendTo(element.parent().parent().parent(".form-checkboxes"));
}
else if (element.attr("name") == "mailing_address") {
error.appendTo(element.parent().parent().parent());
}
else {
error.insertAfter(element);
}
},
submitHandler: function(form) {
// do other things for a valid form
$(form).find(':submit').prop('disabled', true);
setTimeout(function() {
form.submit();
}, 1000);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/jquery.validation/1.16.0/jquery.validate.min.js"></script>
<form id="form-contact-user" method="get" action="">
<fieldset>
<legend>Please provide your name, email address, phone number and zipcode</legend>
<p>
<label for="name">Name (required, at least 2 characters)</label>
<input id="name" name="name" type="text">
</p>
<p>
<label for="email">E-Mail (required)</label>
<input id="email" type="email" name="email">
</p>
<p>
<label for="phone">Phone Number (required)</label>
<input id="phone" type="text" name="phone">
</p>
<p>
<label for="zip">Zip code (required)</label>
<textarea id="zip" name="zip"></textarea>
</p>
<p>
<input class="submit" type="submit" value="Submit">
</p>
</fieldset>
</form>

Hide success and error messages on form

I have one subscription form with ajax. The problem is that success and error messages are always on the page. Why they are on the page and how to hide them until form is submitted?
This is my js function
$(document).ready(function(){
(function($) {
"use strict";
// validate subscribeForm form
$(function() {
$('#subscribeForm').validate({
rules: {
name: {
required: true,
minlength: 4
},
email: {
required: true,
email: true
}
},
messages: {
name: {
required: "Please enter your name?",
minlength: "Your name must consist of at least 4 characters"
},
email: {
required: "Please enter your email address"
}
},
submitHandler: function(form) {
$(form).ajaxSubmit({
type:"POST",
data: $(form).serialize(),
url:"subscribe.php",
success: function() {
$('#subscribeForm :input').attr('disabled', 'disabled');
$('#subscribeForm').fadeTo( "slow", 0.15, function() {
$(this).find(':input').attr('disabled', 'disabled');
$(this).find('label').css('cursor','default');
$('#sub_success').fadeIn();
});
},
error: function() {
$('#subscribeForm').fadeTo( "slow", 0.15, function() {
$('#sub_error').fadeIn();
});
}
})
}
})
})
})(jQuery)
})
And this is the form
<div class="footer-newsletter row footer-widget right-box">
<h3 class="footer-title">newsletter sign up</h3>
<form class="form-inline newsletter-form" id="subscribeForm" method="post" action="">
<input type="text" id="name" name="name" class="form-control" placeholder="Name">
<input type="email" id="email" name="email" class="form-control" placeholder="Email">
<button type="submit" class="btn btn-primary" name="sub_submit">Submit</button>
</form>
<div id="sub_success">You subscribe succesfully!</div>
<div id="sub_error">Opps! There is something wrong. Please try again</div>
</div>
So sub_success and sub_error are always on the page..
Change this following things in your code:-
<div id="sub_success" style="display:none">You subscribe succesfully!</div>
<div id="sub_error" style="display:none">Opps! There is something wrong. Please try again</div>
use this type alert it will gone in 3sec
$('#success_message').fadeIn(1000).html("<div class='alert alert-danger' role='alert' style='font-size: 15px;'>Soory some there is some error,please enter again data...</div>").fadeOut(3000);
Just add .hide on document.ready for both elements as below:
$(document).ready(function(){
$('.sub_success,.sub_error').hide();
});
You could just write a css
#sub_success, #sub_error {display:none}
then with jquery you can just show and hide by using
$("#sub_success").show();
$("#sub_error").hide();

Navigation between html pages on form validation

Working on static pages only.. no backend is present...Hi trying to navigate between html pages, and succeesful in that. But need to switch the page only when the form is properly validate, have tried but its not working..
Need some help...
HTML:
<div class="formContainer">
<form class="form" id="loginForm">
<div class="form-group">
<label>Login</label>
</div>
<div class="form-group">
<label for="loginForm-email">Email address</label>
<input type="email" class="form-control" id="loginForm-email" name="loginForm-email" placeholder="Enter email">
</div>
<div class="form-group">
<label for="loginForm-password">Password</label>
<input type="password" class="form-control" id="loginForm-password" name="loginForm-password" placeholder="Password">
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
</div>
JS:
$(document).ready(function () {
var fnValidate = $("#loginForm").validate({
rules: {
"loginForm-email": {
required: true,
email: true
},
"loginForm-password": {
required: true,
minlength: 5
}
}
});
$('.btn').click(function(e) {
e.preventDefault();
if(fnValidate){
window.location.reload(true);
window.location.href = '../html/userPage.html';
}
else{
alert('hia');
}
});
});
The jQuery validator has custom success and failure callbacks which you can use.
As per your current approach, the fnValidate will return you an object. So you won't know whether it's validated or not. So try using the following approach.
$(document).ready(function () {
$("#loginForm").validate({
rules: {
"loginForm-email": {
required: true,
email: true
},
"loginForm-password": {
required: true,
minlength: 5
}
},
submitHandler: function () {
console.log("inside valid");
window.location.reload(true);
window.location.href = '../html/userPage.html';
// this.submit()
},
invalidHandler: function (event, validator) {
// 'this' refers to the form
console.log("Please fill the form");
}
});
});
jsfiddle example : http://jsfiddle.net/mohamedrias/2vvaN/2/
submitHandler is called only if the form is valid. So there you can submit the form.

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