I have a form with 5 input fields (4 text input, 1 checkbox) and I have written this code to handle missing information in the input fields. The code works fine but but it seems repetitive and inefficient. Is there a simpler way to write this code?
$("#main-form").on('submit', function(event) {
if (!$("#field1").val()) {
event.preventDefault();
$("#field1-error").html("Error!");
}
else
$("#field1-error").html("");
if (!$("#field2").val()) {
event.preventDefault();
$("#field2-error").html("Error");
}
else
$("#field2-error").html("");
if (!$("#field3").val()) {
event.preventDefault();
$("#field3-error").html("Error");
}
else
$("#field3").html("");
if (!$("#field4").val() && !$("#checkbox1").prop('checked')) {
event.preventDefault();
$("#field4-error").html("Error");
}
else
$("#field4-error").html("");
});
If the function does the same thing on multiple similar fields, it is best to just write one function. I think every Javascript engineer at some point or another has banged their head against a wall trying to come up with a slicker way run form validations.
For this situation I would write the function and call it whenever I needed it. Try this:
$("#main-form").on('submit', function(event) {
myValidations.contentsPresent('#field1', '#field1-error');//call the first field validaitions
myValidations.contentsPresent('#field2', '#field2-error');//second
//third
//etc
});
var myValidations =
{
contentsPresent: function(fieldId, errorId)
{
if (!$(fieldId).val()) {
event.preventDefault();
$(errorId).html("Error!");
}
else
$(errorId).html("");
}
},
contentsPresentCheckBox: function(fieledId, checkboxId, errorId)
{
if (!$(fieledId).val() && !$(checkboxId).prop('checked')) {
event.preventDefault();
$(errorId).html("Error");
}
else
$(errorId).html("");
}
}
}
//Try this.
$(document).ready(function(){
/** Form Validation */
$("#formId").validate({
rules: {
field1:{ required: true },
field2:{ required: true },
field3:{ required: true },
field4:{ required: true }
},
messages: {
field1:{ required: 'Field1 is required!' },
field2:{ required: 'Field2 is required!' },
field3:{ required: 'Field3 is required!' },
field4:{ required: 'Field4 is required!' }
}
// Submit function
});
// This is a simple jquery form validation but you need to include the jquery validation plugin.
http://jqueryvalidation.org/
Related
I have a problem with asynchronously validating login in my html form using jQuery Validation Plugin. I want it to send the request asking for login validity on blur, and validate when recieving a response.
This is my code:
var loginAvailability = false;
$().ready(function() {
var gotResponse = false;
$("#form").validate({
onkeyup:false,
rules: {
login: {
required: true,
loginAvailable: gotResponse
}
},
messages: {
login: {
required: "Please enter your login.",
loginAvailable: "This login is already in use."
}
}
});
$("#login").blur(function() {
if($('#login').val()) {
var value = $('#login').val();
$.ajax({
type: "GET",
url: "my server adress"+value,
data: "",
success:function(data){
gotResponse = true;
loginAvailability = data[value] === false;
$("#form").validate().element("#login");
}
});
}
});
});
$.validator.addMethod( "loginAvailable", function( value, element ) {
return loginAvailability;
});
The response from the server is in json format looking like this:
{"chosenLogin": false}
Where false is for a free login, and true is for taken.
I've tested it by putting some console.info() lines inside to see what is happening and the problem is that it never goes to loginAvailable method, so it seems like the rule is never triggered. What can I do to make this work?
I believe to have found an answer. It was as simple as replacing:
loginAvailable: gotResponse
with
loginAvailable: {
depends: function() {
return gotResponse;
}
}
If I run below, and both fields alder and gender is invalid, it'll alert two times. Is it possible to make it alert just once?
$(function(){
$("#formTest").validate({
rules : {
alder : {
required: true
},
gender : {
required: true
}
},
errorPlacement: function (error, element) {
alert("Alert once");
}
});
});
errorPlacement is called once for every error - it's not meant to alert a message, but to place it in the form. You can either try to use the groups feature, to group you fields together and get a single call for the entire group, or use the showErrors function to capture all errors and present them however you like:
$(".selector").validate({
showErrors: function(errorMap, errorList) {
alert(`Your form contains ${this.numberOfInvalids()} errors`);
}
});
Never used jQuery validate before but this might work:
$(function(){
var checked = false;
$("#formTest").validate({
rules : {
alder : {
required: true
},
gender : {
required: true
}
},
errorPlacement: function (error, element) {
if (!checked) {
alert("Alert once");
checked = true;
}
}
});
});
I am using jquery validations in a form. I haven't had many issues, however I did run into a problem in a users form where the jquery number validation isn't firing. I tested it in IE, firefox and chrome and it is not working in any of them. The weird part is that so far it seems that it is specific to this one user's form as when I go to other user forms the alerts fire fine as it does in my testing across all browsers. I was wondering if any one else has come across this problem before when using jquery validation. Below is an example of some of the jquery validation code I am using.
var validator = $("#educationForm").validate({
debug: true,
errorElement: "span",
errorClass: "help-block errortext",
errorPlacement: function (error, element) {
element.before(error);
},
success: function (label) {
label.remove();
},
rules: {
school1GPA: {
number: true
},
school2GPA: {
number: true
},
school1Units: {
number: true
},
school2Units: {
number: true
},
},
onsubmit: false
});
$('.form-actions').on('click', '#btnSubmit', function (evt) {
evt.preventDefault();
if ($("#educationForm").valid()) {
$.ajax({
type: "POST",............
} else {
validator.focusInvalid();
}
});
The issue is that you are triggering evt.preventDefault() before you could even trigger jquery validation. That is basically killing any validation statement following evt.preventDefault(). All you need to is just call $("#educationForm").valid() or jquery.validate() and then call evt.preventDefault().
$('.form-actions').on('click', '#btnSubmit', function (evt) {
if ($("#educationForm").valid()) {
evt.preventDefault(); // prevents the form submission to allow ajax
$.ajax({
type: "POST",............
} else {
validator.focusInvalid();
}
});
You should not need your click handler at all. As per documentation, your ajax belongs inside of the submitHandler callback function.
You also should not set onsubmit to false unless you want validation blocked when the submit button is clicked.
debug set to true will block submission of the form.
Something more like this...
var validator = $("#educationForm").validate({
// debug: true, // <- this is blocking the submit entirely
submitHandler: function(form) {
// your ajax here
$.ajax(...);
return false;
},
errorElement: "span",
errorClass: "help-block errortext",
errorPlacement: function (error, element) {
element.before(error);
},
success: function (label) {
label.remove();
},
rules: {
school1GPA: {
number: true
},
school2GPA: {
number: true
},
school1Units: {
number: true
},
school2Units: {
number: true
},
},
// onsubmit: false // <- this is preventing validation on the submit.
});
DEMO: http://jsfiddle.net/2vv8vL79/
The problem is this jquery validation is not working in my form second time. Its working first time perfectly but second time its shows error message but form is going to submit. The code is here
(function ($, W, D) {
var JQUERY4U = {};
JQUERY4U.UTIL =
{
setupFormValidation: function () {
//form validation rules
$("#aspnetForm").validate({
rules: {
firstname: "required",
lastname: "required",
company: "required",
jobtitle: {
required: true,
},
phone: {
required: true,
number: true
},
email: {
required: true,
email: true
},
},
messages: {
firstname: "Please enter your first name",
lastname: "Please enter your last name",
company: "Please enter your company name",
jobtitle: "Please enter your job title",
phone: "Please enter a valid phone number",
email: "Please enter a valid email address",
},
submitHandler: function (form) {
$('#aspnetForm').on('submit', function (e) {
e.preventDefault();
if (flag) {
createListItem();
}
});
//form.submit(function (e) {
// e.preventDefault();
// if (flag) {
// createListItem();
// }
//});
}
});
}
}
//when the dom has loaded setup form validation rules
$(D).ready(function ($) {
JQUERY4U.UTIL.setupFormValidation();
$('#newsletterModal').on('hidden.bs.modal', '.modal', function () {
clearFields();
});
$('#newsletterModal').on('shown.bs.modal', function (e) {
$('#lblMsg').empty();
});
});
})(jQuery, window, document);
can any one help me
Your submitHandler callback function...
submitHandler: function (form) {
$('#aspnetForm').on('submit', function (e) {
e.preventDefault();
if (flag) {
createListItem();
}
});
}
Do not put a submit event handler inside of the submitHandler callback! It's unclear to me what you're trying to do but the submitHandler callback function of the plugin has already captured & replaced the default submit event of the form.
Also, whenever you declare your own submitHandler function, you are over-riding the default built into the plugin. Since I see nothing inside of your custom submitHandler that submits the form, the form will never be submitted.
You'll either need to remove the submitHandler to allow the form to be submitted (when valid) as per the default functionality OR you'll need to put $(form).submit() inside of it someplace.
submitHandler: function (form) {
if (flag) {
createListItem();
}
$(form).submit();
}
NOTE:
Wrapping up everything like this is superfluous, unnecessary, verbose, and arcane...
(function($,W,D) {
var JQUERY4U = {};
JQUERY4U.UTIL =
{
setupFormValidation: function() {
$("#aspnetForm").validate({ .... });
}
}
$(D).ready(function($) {
JQUERY4U.UTIL.setupFormValidation();
});
})(jQuery, window, document);
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.
The entire mess above can be removed and simply replaced by putting the .validate() method inside of the DOM ready event handler function...
$(document).ready(function() {
$("#aspnetForm").validate({ .... });
});
I am trying to build a custom client side jquery validation and trying to ignore default values that i generate from HTML5 data attributes
$('input, textarea').each(function () {
if ($(this).data('val-default')) {
$(this).focus(function () {
if (this.value == $(this).data('val-default'))
this.value = '';
});
$(this).blur(function () {
if (this.value == '')
this.value = $(this).data('val-default');
});
this.value = $(this).data('val-default');
}
});
So with the above code i can add default values to input and textarea elements like this
data-val-default="Type your first name here"
Placeholder attribute is unfortunately not an option yet
The problem now is that i am trying to validate these elements with Jquery validation like this
$.validator.addMethod("ignoreDefaultValues",
function (value, element) {
if ($(element).data('val-default'))
return !($(element).data('val-default') == element.value);
return true;
},
"Required field"
);
$('form#contact-form').submit(function (e) {
e.preventDefault();
if (!$(this).valid({
rules:
{
title:
{
ignoreDefaultValues: true,
required: true
},
description:
{
ignoreDefaultValues: true,
required: true
},
name:
{
ignoreDefaultValues: true,
required: true
},
email:
{
ignoreDefaultValues: true,
required: true
}
}
})) {
alert("NOT VALID!");
}
else
{
alert("IS VALID!");
//todo: ajax post to server
}
});
Here is an example of an input element
<input type="text" class="firstname" name="firstname" data-val-default="Type your first name here" data-val="true" data-val-required="*" />
The jquery validation seems to ignore the rules. if i test for example by typing an empty space it will validate and alert "NOT VALID" but it just ignores my custom validation.
What am i doing wrong?
Have i missed anything?
You need to setup the validation before the submit function. So instead of doing $(this).valid(...) in your submit handler, instead do this beforehand:
$('form#contact-form').validate( { //your rules
,
submitHandler:function(){
alert('Is Valid!');
$(this).submit(); //or submit via AJAX, or whatever you planned...
},
invalidHandler:function(){
alert('Is not valid!');
}
});