BootstrapValidator how to find rules for a field - javascript

How do I find if there are rules specified for a particular field?
e.g. conditional zip code validation. I want to apply the validation if it hasn't been applied before, otherwise just enable it.
if (zipFieldElements == null) {
$(registerForm).bootstrapValidator('addField', m.zipCodeFieldName, m.getZipCodeValidator());
} else {
bootstrapValidator.enableFieldValidators(m.zipCodeFieldName, true);
}

The solution was to not worry and always call both. This works reliably (0.5.3):
bootstrapValidator.addField(mBehave.stateFieldName, {validators: {notEmpty: "The state cannot be empty"}, container: 'popover'});
bootstrapValidator.enableFieldValidators(mBehave.stateFieldName, true)

Related

How to remove class from body if condition is not met?

I'm working with an if statement to show an alert message depending on certain conditions.
Under the second condition New Article I want a specific css class to be added (show-banner-alert). I am able to get the css added but its now affecting the conditions following it.
I've tried adding a $("body").removeClass and adding a new class with different properties but I am unable to get rid of the first-class successfully.
Here is my code:
$(window).on("load", function(e) {
$('.preloader').fadeOut('slow');
if (document.cookie.includes("isDismissed=true")) {
document.body.classList.add("alert.container");
} else if ("#pageTitle" === ("New Article") !== "-1") {
document.body.classList.add("show-banner-alert");
} else if ("#pageTitle".indexOf("Test") !== "-1") {
$("body").removeClass("show-banner-alert").addClass("show-alert");
} else if ("#pageTitle".indexOf("New Home") !== "-1") {
document.body.classList.add("show-alert");
}
});
first :
none of the conditions are correct.
all the if conditions are going to give you a correct answer ( true ).
second :
try either using jquery or using vanilla js for dom manipulation. ( I'd recommend jquery).

Compare duplicate values of two select in materializecss framework

I have two select boxes and i dont want that the user choose the same value in both.
I've tried some solution proposed on stack, but the materialized select is different from "normal select" as contains the options in list item elements.
However, i came up with a solution, which is all but elegant, i know..im a novice with these things.
But its not working as i intended.
I want to create an additional method for jquery validation plugin, in the example on fiddle i've inserted an additional field to show the error placement.
I think is pretty simple, but i just can't figure out how to do it...
$.validator.addMethod("checksameval", function(value, element) {
return $('#pref1').val() == $('#pref2').val()
}, "Pref1 and Pref2 cant have same value!");
https://jsfiddle.net/L24otmaa/5/
edited with custom method (still not working..)
The problem with your solution is that the form will still be valid and therefore it will be possible to send it anyway.
You have to add a custom validation. The plug-in offers a callback where you can check whatever you want before you finally submit it.
This can be done by adding your validation to a custom submit handler
var isSameValue = function() {
var val1 = $('#pref1').val();
var val2 = $('#pref2').val();
if (val1 == val2) {
$customErrorDiv.text('error you cant select same value twice!!');
return true;
}
$customErrorDiv.text('');
return false;
}
// check also on runtime
$('.course').change( function() {
isSameValue();
});
$("#application").validate({
// check before submitting
submitHandler: function(form) {
if (isSameValue()) {
return;
}
// submit the form manually
form.submit();
}
});
Fiddle: https://jsfiddle.net/7uhkddrx/
Documentation: https://jqueryvalidation.org/validate/
Of course you would have to style this message according to your needs.
EDIT: By the way: currently your select boxes are not set to be required.
EDIT2: added checking on runtime

bootstrapValidator: How do you add and remove validators dynamically to an existing input field?

I have a dynamic form that is bound with knockout.js and validated by bootstrapValidator.
There is one input field that needs to be 'required-validated' dependent on the state of another control.
The input field:
<textarea id="inputReason" name="inputReason" rows="3"
class="form-control col-lg-8"
data-bind="value: Reason" />
The relevant javascript part of the knockout-viewmodel:
self.SelectAbsenceType = function (absenceType) {
self.SelectedID(absenceType.ID);
if (self.SelectedAbsenceType().ReasonRequired) {
$('#formCreate').bootstrapValidator('addField', 'inputReason', {
validators: {
notEmpty: {
message: 'Please enter a reason'
}
}
});
} else {
$('#formCreate').bootstrapValidator('removeField', 'inputReason');
}
}
The problem I'm facing is that a call to removeField of the bootstrapValidator instance doesnt seem to completely remove all registration infos since there is a javascript exception in the updateStatus method of the bootstrapValidator class that in fact should not be called at all since I have the removed the field before:
var that = this,
type = fields.attr('type'),
group = this.options.fields[field].group || this.options.group,
total = ('radio' === type || 'checkbox' === type) ? 1 : fields.length;
The exception: Unable to get value of the property 'group': object is null or undefined
The variable field contains the value 'inputReason'.
So my Question is this (because the documentation of bootstrapValidators removeField is not entirely clear on this: How do I remove the dynamically added validation of the field inputReason completey?
(side note: can someone add the tag boostrapvalidator?)
Ok, after some digging it seems that the bootstrapValidator Plugin simply doesnt yet support the removal of validators that are attached to an input field that is NOT to be removed in the same process. Thus the events that are attached to the input field that trigger the validation are not unregistered.
A temporary workaround is to destroy the bootstrapValidator instance, set the data-* attribute of the form to null and reinitialize the plugin. This code replaces the bootstrapValidator.removeField() call:
bootstrapValidator.destroy();
$('#formCreate').data('bootstrapValidator', null);
$('#formCreate').bootstrapValidator();
update
Another even better way to get this done is to use the enable/disable feature of bootstrapValidator:
bootstrapValidator
.enableFieldValidators
(
'inputReason',
self.SelectedAbsenceType().ReasonRequired
);
(thanks to #nghuuphuoc for pointing this out)

Run a webshim "addCustomValidityRule"

I check if one of two text inputs have text, using webshim, and think custom-validity sounds correct.
http://afarkas.github.io/webshim/demos/demos/webforms/4-webforms-custom-validity.html
There is a method called addCustomValidityRule that looks like this:
$.webshims.addCustomValidityRule('testname', function (elem, value) {
if (value && $(elem).hasClass('test-class') && value != 'foo bar baz') {
return true; //means yes, it's not valid
} else {
return false; //no, it is valid
}
}, 'you have to enter foo bar baz');
But I can't find any way to trigger it. How do I trigger or run it on "submit click"?
#David Larson
HTML5 form validation uses setCustomValidity to mark inputs as invalid with a customError. Unfortunatley a field as to be marked as invalid as soon as possible (submit-event is too late).
This means, if you use this helper addCustomValidityRule, it will run the function instantly on all input, select and textarea elements and also if it detects a change. (change event).
If you want to invoke this function simply trigger the event 'refreshCustomValidityRules' on the given element.
Found another way to soulve this, if anyone know the answear on my original question please tell, good to know anyway :)
Simple like this with webshim:
#Html.TextBoxFor(x => x.MessageHeader)
<textarea id="MessageText" name="MessageText" data-dependent-validation='{"from": "MessageHeader", "prop": "required", "toggle": true}' />
More info about this here:
http://afarkas.github.io/webshim/demos/demos/webforms/4-webforms-custom-validity.html

jQuery validate - adding a rule causes validation to fire

I have code like below to perform some conditional validation on fields in my form. The basic idea being that if something is entered in one field, then all the fields in this 'group' should be required.
jQuery.validator.addMethod('readingRequired', function (val, el) {
//Readings validation - if a reading or a date is entered, then they should all be ntered.
var $module = $(el).closest('tr');
return $module.find('.readingRequired:filled').length == 3;
});
//This allows us to apply the above rule using a CSS class.
jQuery.validator.addClassRules('readingRequired', {
'readingRequired': true
});
//This gets called on change of any of the textboxes within the group, passing in the
//parent tr and whether or not this is required.
function SetReadingValidation(parent) {
var inputs = parent.find('input');
var required = false;
if (parent.find('input:filled').length > 0) {
required = true;
}
if (required) {
inputs.addClass("readingRequired");
}
else {
inputs.removeClass("readingRequired");
}
}
//This is in the document.ready event:
$("input.reading").change(function () {
SetReadingValidation($(this).closest("tr"));
});
This works fine, and I've used pretty much the same code on other pages with success. The slight problem here is that when i enter a value into the first textbox and tab out of it, the validation fires and an error message is displayed. This doesn't happen on other pages with similar code, rather the validation waits until the form is first submitted. Does anybody have any idea why this might be happening?
Hmm. You know how it goes, post a question and then find a solution yourself. Not sure why this works exactly, but changing my binding from:
$("input.reading").change(function () {
SetReadingValidation($(this).closest("tr"));
});
to
$("input.reading").blur(function () {
SetReadingValidation($(this).closest("tr"));
});
Seems to have solved this issue. Would still appreciate being enlightened as to why that might be...

Categories