Customizing a password strength validator plugin - javascript

I am using a plugin called pStrength.jquery.js and for some reason its not submitting the form I have, or it is submitting the form even if it is not supposed to (when I changed the code)
The code i am using is:
$(document).ready(function () {
$('#myForm').submit(function () {
return false;
});
$('#myElement1, #myElement2').pStrength({
'changeBackground': false,
'onPasswordStrengthChanged': function (passwordStrength, strengthPercentage) {
if ($(this).val()) {
$.fn.pStrength('changeBackground', this, passwordStrength);
} else {
$.fn.pStrength('resetStyle', this);
}
$('#' + $(this).data('display')).html('Your password strength is ' + strengthPercentage + '%');
},
'onValidatePassword': function (strengthPercentage) {
$('#' + $(this).data('display')).html(
$('#' + $(this).data('display')).html() + ' Great, now you can continue to change your password!');
$('#myForm').submit(function () {
return true;
});
}
});
});
Someone has told me that I should use booleans and inside the validation checks, set it to true or false.
The problem is that i have no idea how to do this
Is there anyone that could help me and show me the code to do this?
Thank you in advance

The reason it was still submitting was because the onValidatePassword function runs on each individual field, whereas you actually had two fields to validate. If one field validates and the other doesn't, the form would still submit because the Boolean had already been set to true, which was the only condition needed to submit.
Updated code below, you can also refer to the fiddle.
$(document).ready(function () {
$('#myForm').submit(function (event) {
// TODO: check that the two field values match as well
if ($('#myElement1').data('valid') === 'yup' &&
$('#myElement2').data('valid') === 'yup') {
// remove these three lines to make it submit
alert('Submitting...');
event.preventDefault();
return false;
// and uncomment this one line
//return true;
} else {
event.preventDefault();
return false;
}
});
$('#myElement1, #myElement2').data('valid', 'nope');
...
Your complete onValidatePassword callback should now look like this:
'onValidatePassword': function (strengthPercentage) {
$('#' + $(this).data('display')).html(
$('#' + $(this).data('display')).html() + ' Great, now you can continue to change your password!');
formValid = strengthPercentage >= 60;
// set for each element
if (strengthPercentage >= 60) {
$(this).data('valid', 'yup');
} else {
$(this).data('valid', 'nope');
}
}

Inside your onValidatePassword, you're binding to the submit event, instead of submitting the form. Replace this code:
$('#myForm').submit(function () {
return true;
});
with
$('#myForm').submit();

Related

Return false; does not work in jquery .each function

Before posting this question I tried StackOverflow but did not find the answer.
So, the question is, I have an array with some values(suppose 4,6,7,8,10 etc). I used the .each function of jquery to prompt the alert message. but my code gives me an alert message, focus to the desired input box and submit the form and does not "return false".
I want it to return false after focusing.
$(document).on('keypress','#create_invoice',function(){
$.each(newArr, function( i, l ){
//alert( "Index #" + i + ": " + l );
if($.trim($('#item_name'+l).val()).length == 0)
{
alert("Please Enter Item Name");
$('#item_name'+l).focus();
// return false; //if use this not work and submit form
}
//return false; //if use this not work and submit form
});
//return false; if i use this then submit() not work
$('#invoice_form').submit();
});
The return false works, but I think what you want is to stop the form from submitting if you returned false. That behavior can be done with this;
First put an e in the function argument then use e.preventDefault();.
What's next is make a variable that would be a boolean which would determine if you can allow the form to submit. In the code below, I used var allowSubmit.
Try the code below.
$(document).on('keypress', '#create_invoice', function(e) {
e.preventDefault();
// boolean variable
var allowSubmit = true;
$.each(newArr, function(i, l) {
if ($.trim($('#item_name' + l).val()).length == 0) {
alert("Please Enter Item Name");
$('#item_name' + l).focus();
// set the variable to false
allowSubmit = false;
return false;
}
});
// check if we could submit the form
if (allowSubmit) {
$('#invoice_form').submit();
}
});

jQuery form validation check ending up in a loop

I'm very new if it comes to jQuery. I'm trying to make a good client-side validation for my form. (At the moment only checking if X field is not empty)
But when I submit the form I end up in a forever loop.
I can explain the problem, and I understand the 'why'. But I have no idea how to fix it.
The problem occurs because:
Everytime I submit the form, he runs the validation check again, then submits when there aren't any errors, but because I submit, he checks again-- and so on.
With this code I monitor if the form is getting submitted. (And if so, let the validation begin)
// Form validation on submitting the form
$('form').on('submit', function() {
var id = $(this).attr('id');
console.log('Form is submitted');
submitFormValidation(id);
});
With this code I'm trying to validate every input field.
function submitFormValidation(id) {
event.preventDefault();
var goodCount = 0;
var goodCountMinimum = $('#' + id + ' .c-contact-form-item-input').length;
$('#' + id + ' .c-contact-form-item-input').each(function () {
if ($(this).val().length == 0) {
$(this).parent().find('span').css('background-color', 'red');
$(this).parent().find('span').css('width', 'calc(100% - 30px');
$(this).parent().find('i').css('background-color', 'red');
$(this).parent().find('i').css('animation', 'none');
$(this).parent().find('i').css('opacity', '1');
}
else {
$(this).parent().find('span').css('background-color', 'green');
$(this).parent().find('span').css('width', 'calc(100% - 30px');
$(this).parent().find('i').css('background-color', 'green');
$(this).parent().find('i').css('animation', 'none');
$(this).parent().find('i').css('opacity', '1');
goodCount = goodCount + 1;
return goodCount;
}
});
if (goodCount == goodCountMinimum) {
$('#' + id).submit();
}
}
I hope someone can help me out on how to fix the never ending loop.
Thanks!
Try changing...
$('#' + id).submit();
to...
$('#' + id)[0].submit();
The difference between these two is that the first triggers a submit on the jQuery object, where the second triggers a sumbit on the raw Element. Triggering a submit on the Element, and not the jQuery object, should result in the jQuery submit event handler being skipped.
Example...
$('form').on('submit', function(e){
console.log('submitted!');
e.preventDefault();
setTimeout(function(){
e.target.submit();
}, 5000);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="http://www.google.com/">
<button>Go!</button>
</form>
Change
if (goodCount == goodCountMinimum) {
$('#' + id).submit();
}
To
if (goodCount == goodCountMinimum) {
return;
} else {
e.preventDefault();//pass in the event object to the function
}
For this solution to work, change your function to take two parameters:
function submitFormValidation(id, e) {}
And invoke it like this:
$('form').on('submit', function(e) {
var id = $(this).attr('id');
console.log('Form is submitted');
submitFormValidation(id, e);
});
If you submit the form (using jQuery's submit()), the jQuery submit event handler will continuously be called. Just returning will allow the default action of the form to be taken (which is submitting).

jQuery multiple inputs with one Function RegExp

I've got a form with more than 1 inputfields. The format that should be allowed is hh:mm / h:mm. So I already have a function, that checks my input if the format is true inbstandly on input.
So what I want is, if i click on my submit button i'd like to check all the boxes again if the format is right. If true then submit(); else then alert() or something. But that isnt the problmem.
I have no idea how i can realize this. Thank you in advance :))
function validateAbs(inputField) {
var isValid = /^([0-1]?[0-9]|2[0-3]):([0-5][0-9])(:[0-5][0-9])?$/.test(inputField.value);
if (isValid) {
inputField.style.backgroundColor = '#bfa';
} else {
inputField.style.backgroundColor = '#fba';
}
return isValid;
}
$(function(){
$('#ist').on('input', function() {
//This is one of ne hh:mm Textboxes
validateAbs(this);
});
});
$(function(){
$('#abssubmit').on('input', function() {
//This is my Submit-Button
});
});
It's surprisingly easy:
$('#abssubmit').on('input', function() {
$("selector-for-the-inputs-you-want-to-check").each(function() {
validateAbs(this);
});
});
If you want to know whether any of them is invalid, you can use filter:
$('#abssubmit').on('input', function() {
var invalidFields = $("selector-for-the-inputs-you-want-to-check").filter(function() {
return !validateAbs(this);
});
if (invalidFields.length) {
// At least one field was invalid
}
});
You will need to change to a submit handler not an 'input' handler:
$('#abssubmit').on('submit', function(ev) {
var isValid;
ev.preventDefault(); // to stop the form from submitting
$('#ist').each(function() {
if (!validateAbs(this)) isValid = false;
});
if (isValid) {
this.submit(); // all the validations succeeded
}
});

jQuery empty input check function not working as expected

This question has been done to death on SO and I'm really, really sorry! I've already taken the bones of the below idea from a couple of SO questions on the same theme.
All said though, I still can't get it to work as expected.
It works OK if NONE are filled in.
It works OK if the END input is filled in and not the others.
It works OK if the MIDDLE input is filled in.
If you fill in ONLY the FIRST input though, it alerts, but submits anyway?
JSFIDDLE
$(document).ready(function (e) {
// completed count submit handler
$("#submit_counts_button").on('click', function () {
window.incomplete = false;
$('input[type=number]').each(function () {
if ($(this).val().length == 0) {
window.incomplete = true;
alert('Some fields are empty');
return false;
} else {
if (window.incomplete === false) {
$("#submit_counts_button").prop('disabled', true);
$("#submit_counts_button").html('Please Wait ...');
//$("#update_form").submit();
}
}
});
});
});
I'm sure it's something totally embarrassingly obvious but after a 16 hour day, I just can't see it. Any help appreciated ...
You need to pull the 'incompletion' check outside of the .each
$(document).ready(function (e) {
// completed count submit handler
$("#submit_counts_button").on('click', function () {
window.incomplete = false;
$('input[type=number]').each(function () {
if ($(this).val().length == 0) {
window.incomplete = true;
alert('Some fields are empty');
return false;
}
});
if (window.incomplete === false) {
$("#submit_counts_button").prop('disabled', true);
$("#submit_counts_button").html('Please Wait ...');
//$("#update_form").submit();
}
});
});
http://jsfiddle.net/6WpeF/6/
try
if(document.getElementById('id of input').value != ""){}

Re-enabling Submit after prevent default

I am trying to unbind or reenable the prevent default so my form will submit on good data.
I have tried multiple examples. Here is my code and some of the examples i tried.
This code works great for what i want to. Just the last thing and resetting the div which i can implement after i get this.
function lengthRestriction(elem, min, max) {
var uInput = elem.value;
if (uInput.length >= min && uInput.length <= max) {
return true;
} else {
var cnt = document.getElementById('field');
cnt.innerHTML = "Please enter between " + min + " and " + max + " characters";
elem.focus();
$('#ShoutTweet').submit(function(e) {
e.preventDefault();
//bind('#ShoutTweet').submit();
//$('#ShoutTweet').trigger('submit');
});
}
}​
i have a jsbin set up too http://jsbin.com/ebedab/93
Don't try to set up and cancel a submit handler from within your validation function, do it the other way around: call the validation from within a single submit handler, and only call .preventDefault() if the validation fails:
$(document).ready(function() {
$('#ShoutTweet').submit(function(e) {
if (/* do validations here, and if any of them fail... */) {
e.preventDefault();
}
});
});
If all of your validations pass just don't call e.preventDefault() and the submit event will then happen by default.
Alternatively you can return false from your submit handler to prevent the default:
$('#ShoutTweet').submit(function(e) {
if (!someValidation())
return false;
if (!secondValidation())
return false;
if (someTestVariable != "somevalue")
return false;
// etc.
});
I'm not completely sure what you are asking, but if your goal is to destroy your custom submit handler, then use this:
$("#ShoutTweet").unbind("submit");
This assumes that you have a normal (not Ajax) form.
Just call submit on the form
$('#ShoutTweet').submit();
This works surely and enable form submission after event.preventDefault();
$('#your-login-form-id').on('submit', onSubmitLoader);
function onSubmitLoader(e) {
e.preventDefault();
var self = $(this);
setTimeout(function () {
self.unbind('submit').submit(); // like if wants to enable form after 1s
}, 1000)
}

Categories