Navigation between html pages on form validation - javascript

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.

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

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.

Trouble with validate() on jquery

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

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

Categories