jquery validate with if statement in custom method - javascript

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

Related

How change JQuery Validation Message without refreshing website [duplicate]

This question already has answers here:
jquery .validate() variable error message
(3 answers)
Closed 1 year ago.
I am using jQuery Validation from here: https://jqueryvalidation.org. Currently, I have two types of Messages prepared. They are popping out. When I'm changing language on web variables global variable with messages also is changing, but message in validator don't. Language of the validator change after I refresh the website. How can I change it on live without refreshing the website?
HTML is no needed, because everything is happening in JS file.
This is a function that are changing values in the object.
JS:
function setLang(lang) {
(lang) ? lang: "pol";
if (lang == "pol") {
Messages = {
formFirstnameRequired: 'Pole imie jest wymagane!',
formLastnameRequired: 'Pole nazwisko jest wymangane!',
formEmailRequired: 'Pole email jest wymagane!',
formTitleRequired: 'Pole Tytuł jest wymagane!',
formMessageRequired: 'Pole wiadomość jest wymagane!',
}
} else if (lang == "eng") {
Messages = {
formFirstnameRequired: 'Field firstname is required!',
formLastnameRequired: 'Field lastname is required!',
formEmailRequired: 'Field email is required!',
formTitleRequired: 'Field title is required!',
formMessageRequired: 'Field message is required!',
}
}
}
I'm also using this cookie for managing the language of this form validation:
if (getCookie("lang") == null) {
document.cookie = 'lang=pol';
}
setLang(getCookie("lang"));
$(".nav").on("click", "#polLang", (event) => {
document.cookie = 'lang=pol';
setLang(getCookie("lang"));
});
$(".nav").on("click", "#engLang", (event) => {
document.cookie = 'lang=eng';
setLang(getCookie("lang"));
});
Here I have validation
JS:
$("#contactForm").validate({
rules: {
"formFirstname": {
required: true,
},
"formLastname": {
required: true,
},
"formEmail": {
required: true,
},
"formTitle": {
required: true,
},
"formMessage": {
required: true,
}
},
messages: {
"formFirstname": {
required: Messages.formFirstnameRequired,
string: true
},
"formLastname": {
required: Messages.formLastnameRequired,
string: true
},
"formEmail": {
required: Messages.formEmailRequired,
email: true,
},
"formTitle": {
required: Messages.formTitleRequired,
string: true
},
"formMessage": {
required: Messages.formMessageRequired,
string: true
}
},
onfocusout: false,
errorPlacement: function(error) {
toastr.error(error);
},
submitHandler: function(form) {
toastr.success('success')
return false;
},
invalidHandler: function() {
return;
}
});
Jquery validator msgs are static. If you want to update them dynamically you can create a function, that will return a new msg.
Like this:
"formFirstname": {
required: function getFormFirstname() { return Messages.formFirstnameRequired },
string: true
},

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/

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