Variable dependent rule in jQuery validation - javascript

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

Related

jquery number validation not working consistently

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/

Jquery validation not working second time

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

Simplifying Form validation

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/

jquery validate with if statement in custom method

I am using the validate plugin for jquery and have the following custom method:
$.validator.addMethod("username", function(value, element) {
if (element.prop("required")) {
var re = new RegExp('^([FG]?\\d{5}|\\d{5}[AB])$');
} else {
var re = new RegExp('^'+element.defaultValue+'|^([FG]?\\d{5}|\\d{5}[AB])$');
}
return re.test(value);
});
The if statement returns the error element.prop is not a function.
I've also tried $(this).prop... and although I don't get any errors it always runs the else part of the statement.
Is there anything else I can use instead to achieve this??
EDIT:
Here's the call:
$("#myform").validate({
debug: true,
ignore: ".ignore",
rules: {
field: {
required: {
depends: function() {
return $(this).prop("required");
}
},
username: true,
}
},
messages: {
field: {
username: "Enter a valid username"
}
},
success: function(label) {
label.text("Good result!");
},
submitHandler: function() {
alert("submitted!");
}
});
I think you should use:
if ($(element).prop("required")) {
you may be using older jQuery version:
try $(element).attr("required")

jQuery validation using values in array

I have a simple form and would like to add a custom jQuery validation rule. I would like the text field (bonuscode) to only have a handful of possible values. I assume I need an array of those values, but not knowing much javascript, I don't know where I'm going wrong here.
jQuery.validator.addMethod("equals", function(value, element, param) {
return this.optional(element) || value == param;
}, jQuery.format(""));
$(document).ready(function(){
$("#form").validate({
debug: false,
rules: {
bonuscode: {equals: ["code1", "code2"]}
},
messages: {
bonuscode: "That's not a Bonus Code!",
},
});
});
Having the bonus value in the javascript array is not a good solution. You can make the ajax request to the server and check the bonus value. Here is the sample code.
You can use the remote option in the validation plugin to check the bounus
$("#form").validate({
debug: false,
rules: {
bonuscode: {
required: true,
remote: {
url: "check-bonus.php",
type: "post",
data: {
bonuscode: function() {
return $("#bonuscode").val();
}
}
}
}
}
});
Assuming this is actually your use case, #jems is probably correct in saying you should check this kind of thing in server-side code. However, your custom rule is not far off:
jQuery.validator.addMethod("equals", function(value, element, param) {
return this.optional(element) || $.inArray(value, param) >= 0; // <-- Check if the value is in the array.
}, jQuery.format(""));
$(document).ready(function() {
$("#form").validate({
debug: false,
rules: {
bonuscode: {
equals: ["code1", "code2"]
}
},
messages: {
bonuscode: "That's not a Bonus Code!",
},
});
});
Example: http://jsfiddle.net/AApJx/

Categories

Resources