parsley.js dynamic error message - javascript

I am using parsley.js with the custom validator on a select box.
I want the error message on the validator to use the currently selected option in the select box + some more text.
Unfortunately, it seems as if I am unable to change the error message dynamically.
My code
window.Parsley
.addValidator('attachedEmployee', {
requirementType: 'string',
validateString: function(value, arg1, arg2, arg3) {
var employeeID = $("#medarbejder_navn").val();
//No employee is selected if ID is 1
if(employeeID == 1)
{
//Only shifts which can be made with no employees are "accepted" and "free"
if(value == "G" || value == "L" || value == "A")
return true;
else
{
return false
}
}
else
return true;
},
messages: {
da: "%s"
}
});
It would seem the the validator adds the error message as soon as it gets attached, meaning it is locked right from the get go.
Anyone know how to get around this problem?

Just struggled with this, found the answer in multiple custom error message support per field by using parsley.js
To change the error message I'm doing this now:
window.Parsley
.addValidator('atLeast', {
validateString: function(value, requirement){
window.Parsley.addMessage('en', 'atLeast','Fill at least ' + requirement + ' input');
return this.validateAtLeast(Number(requirement)); // custom function
},
});

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

i have a form with few input fields with class "inputfields" need to validate each field if empty alert 'fieldname is empty' otherwise return true my jquery code is not working keep getting errors at the console log can any one help please ?
jQuery(document).ready(function() {
$('.inputfields').each.on('change keyup' ,function(){
var ope = $(this).attr('name');
if (ope.val()==''){
alert(ope+'is empty');
}else {
console.log(ope);
}
});
});
I believe you want to check different types of input fields, hence want to use change and keyup.
I tried something based on your code, but this following solution will only work, if you want to validate text type input fields. For select or other input types you have to put some more checks inside the loop or have to some other way to validate.
$('.inputfields').each(function() {
$(this).bind('change keyup', function() {
var ope = $(this).attr('name');
if ($(this).val() == '') {
console.log(ope+'is empty');
} else {
console.log(ope+ ' : ' + $(this).val());
}
});
});
Hope this will lead you to find your desired solution.

Popup - if user enters bad input, how can I get it to error on submit

I have a popup on my page that has a typeahead input on it. Right now you can type garbage and click submit and it lets you. I'm trying to write code that will throw an error on the popup if you type something that isn't included in the typeahead options and it won't let you submit it until you fix it. Here is my code, it is for making a school schedule that has classes in the typeahead dropdown.
var schedule = schedule.content.get();
var validClasses = Fp.filter(schedule.classes, function (class) { return !class.passed; }),
inputClasses = $('.optimizeViaClasses input.className').map(function () { return $(this).val(); }),
isErrorForValidClasses = Fp.all(inputClasses, function (inputClass) { return Fp.contains(validClasses, inputClass); });
if(validClasses !== inputClasses){
$errorMessage.text('Your selection does not match the class(es) in the current schedule!');
$errorMessage.show();
}
Right now if you enter garbage in the input field, this will throw an error but still let the user submit. How can I stop the user from submitting until the input is correct?
Here is my button:
$submitBtn.on('click', function(event){
if(inputParameters() !== false){
$myPopUp= $modal.find('#myData').detach()[0];
}
event.preventDefault();
});
and I checked the output of inputClasses in the Google developer console, it outputs the class and a prevObject. I just need the class...
Let javascript return either True or false and if the popup comes out return false other wise true.
For instance if it get into if return false other wise true.
since you modified your code i suppose you might want to try this instead:
http://api.jquery.com/event.stoppropagation/
also you might want to be doing something along the lines of this if stoppropagation does not result in the desired effect:
$("#formid").on("submit",function(e){
// declare isValid outside of this and set it in your validation function or call it inside this and check for that.
if(isValid) {
e.stopPropagation();
}
});
at least that's how i went about solving such issues usually. i hope it helps.
got it. the error i had was throwing an error.
var schedule = schedule.content.get(),
validClasses = Fp.filter(schedule.classes, function (class) { return !class.passed; }),
inputClasses = $('.optimizeViaClasses input.className').map(function () { return $(this).val(); }),
actualValidClasses = Fp.pluck(validClasses, 'className');
$.each(inputClasses , function(index, value){
if($.inArray(value, actualValidClasses ) === -1){
$errorMessage.text('Your selection does not match the class(es) in the current schedule!');
$errorMessage.show();
error = true;
return false;
}
});

How to check all text boxes are empty before clicking calculate

Hi all im new to jscipt,,, well, programming in general to be honest, but learning slowly for personal use.
I seek guidence on how i could place all the textboxes(inputs) in my index file into a list container, loop through them to check if they are empty or not before clicking the calculate button. If they are empty then inform the user of which one is empty.
Also, is there a way of preventing users from entering text into the textboxes and numbers only.
Background: im creating a form that requires all fields to be populate with numbers(in hours), a graph will then be generated from those values.
ive placed the file in skydrive for folks to download with the link below.
Index file
I did try the following but this alerts me regardless of weather the texboxes are populate or not.
function checkInputsGenerateGraph()
{
if( $('#hutz-hoursInput').val() == ""||$('#hutz-weeksPerYearInput').val() == ""||$('#hutz-jobsPerWeekInput').val() == ""||$('#hutz-hourlyMachineRateInput').val() == ""||$('#hutz-maintneneceDowntimeInput').val() == ""||$('#hutz-scrapRateInput').val() == ""||$('#hutz-toolsPerJobInput').val() == ""||$('#hutz-timeToLoadToolInput').val() == ""||$('#hutz-timeToSetPartsInput').val() == "")
{
alert('One them is empty!!');
}
else
{
$("#hutz-graph").slideDown();
$("#hutz-lblImproveMyProcess").slideUp();
$("#hutz-hoursInput").slideUp();
$("#hutz-weeksPerYearInput").slideUp();
$("#hutz-jobsPerWeekInput").slideUp();
$("#hutz-ourlyMachineRateInput").slideUp();
$("#hutz-ntneneceDowntimeInput").slideUp();
$("#hutz-scrapRateInput").slideUp();
$("#hutz-toolsPerJobInput").slideUp();
$("#hutz-timeToLoadToolInput").slideUp();
$("#hutz-timeToSetPartsInput").slideUp();
$("#hutz-lblMachineDetails").slideUp();
$("#hutz-lblPartSetting").slideUp();
$("#hutzcurrencyPreferenceInput").slideUp();
createChart();
}
}
First off, give all the required elements a common class, for examples sake we'll call this required:
<input type="text" class="required" id="hutz-hoursInput" />
Then, when your checkInputsGenerateGraph() function is called, you can loop over the required elements and check them:
$('.required').each(function() {
if (this.value.length == 0) {
alert(this.id + ' is empty!');
}
});
You could also do something like the following to remove all non-digits from your inputs:
$('.required').change(function() {
this.value = this.value.replace(/[^\d]+/, '');
});
See it in action
Hope that points you in the right direction!
edit
Here's a complete example:-
function checkInputsGenerateGraph() {
var isValid = true;
$('.example').each(function() {
if (this.value.length == 0) {
alert(this.id + ' is empty!');
isValid = false;
}
});
if (isValid) {
alert('do calculations!');
}
}
So, loop over all of the elements first, and make sure they are all populated. If not, set isValid to false so that once the loop completes, the calculations are not performed.

Callback/validation tips for jeditable

Any tips for form validation using jeditable. I would like to have the script POSTed to pass back errors with JSON, with the submitted text but can't seem to figure that one out, if even possible. Or how to check text as it's being inputed via onChange.
Thx
Here is a simple sample, but not used jQuery Validation.
function isNumeric(value) {
if (value == null || !value.toString().match(/^[-]?\d*\.?\d*$/)) return false;
return true;
}
$('.edit').editable(your_url, {
onsubmit: function(settings, original) {
if (isNumeric(original)) {
return true;
} else {
//display your message
return false;
}
}
});

Categories