jQuery validation using values in array - javascript

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/

Related

How do I trigger a jQuery code while using the jQuery validation library?

I am using jQuery validation library to validate both password inputs to have the same value. My code is written below.
$(".woocommerce-ResetPassword").validate({
onfocusout: false,
onkeyup: false,
rules: {
password_2: {
equalTo: "#password_1"
}
},
messages: {
password_2: "<div class='woocommerce-password-strength bad'>Passwords do not match</div>"
},
submitHandler: function(form) {
return true;
}
});
I want to execute a jQuery code to add a class to an element when the notification of password_2 appears.
I want to modify this part of the code by adding a jQuery script inside the messages: {} but the code below does not work. You can see that I added $(".woocommerce-form-row--last").addClass("notif-triggered");
messages: {
password_2: "<div class='woocommerce-password-strength bad'>Passwords do not match</div>"
$(".woocommerce-form-row--last").addClass("notif-triggered");
},
Any help is greatly appreciated. Thanks.
You don't tell us, but I'll assume you're using the validation library linked here.
You should be able to add functionality within an invalidHandler, e.g. something think this:
$(".woocommerce-ResetPassword").validate({
onfocusout: false,
onkeyup: false,
rules: {
password_2: {
equalTo: "#password_1"
}
},
messages: {
password_2: "<div class='woocommerce-password-strength bad'>Passwords do not match</div>"
},
submitHandler: function(form) {
$(".woocommerce-form-row--last").removeClass("notif-triggered");
return true;
},
invalidHandler: function(event, validator) {
$(".woocommerce-form-row--last").addClass("notif-triggered");
}
});

Variable dependent rule in jQuery validation

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

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/

Multiple instances of jQuery Validation Plugin on a JSP page

SOLVED: $.extend() twice in a row simply overwrites the previous object because objects are passed by reference. My fix was to do this:
var updateUserObj = $.extend({}, validationPluginDefaults);
var newUserObj = $.extend({}, validationPluginDefaults);
Then the validators are executed like this:
var whateverValidator = $.extend(updateUserObj,{new rules})
Update: Further research shows that what I'm trying to do appears to be correct but the problem may be in the object I am extending - "validationPluginDefaults"). Here it is below:
var validationPluginDefaults = {
ignore: [],
errorElement: 'p', //default input error message container <p>
errorClass: 'text-error', // default input error message class
focusInvalid: true, //focus on the first invalid field
messages: {},
invalidHandler: function (event, validator) { //display error alert on form submit
},
highlight: function (el) { // hightlight error inputs
//jQuery(el).closest('.control-group').addClass('error'); // set error class to the control group
},
success: function (err, el) {
jQuery(el).next(".text-error").hide();
jQuery(el).next(".text-error").remove();
},
errorPlacement: function (error, element) {
error.insertAfter(element);
},
onfocusin: function () {},
onfocusout: function () {}
};
From my testing it appears that even though I have two separate forms on a JSP page and each has different validation that I can still only use one jQuery Validate Plugin instance per page; is this correct?
Here's my code:
// Define validation rules for form one
var formOneValidator = $.extend(validationPluginDefaults,{
rules: {
firstName: {
minlength: 2,
onlyAlphaAndHyphen: true,
required: true,
},
lastName: {
minlength: 2,
required: true,
},
email: {
required: true,
email: true
}
}
});
var formTwoValidator = $.extend(validationPluginDefaults,{
rules: {
newFirstName: {
minlength: 2,
onlyAlphaAndHyphen: true,
required: true,
},
newLastName: {
minlength: 2,
required: true,
},
newEmail: {
required: true,
email: true,
}
}
});
$("#formOne").validate(formOneValidator);
$("#formTwo").validate(formTwoValidator);
What happens here is that formOne validator takes on all the rules of formTwoValidator after this code executes.
Is the solution to have only one validator and swap out rules depending on which form I'm in? It just seems strange that I wouldn't be able to define separate validators for each form on the page. Am I fundamentally misunderstanding something here?
you could use knockout and give each page a different view model which handles the different validation. That is how i would do it but i'm sure there will be a better answer.

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")

Categories

Resources