Run a webshim "addCustomValidityRule" - javascript

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

Related

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)

Cannot return from outside a function or method?

While developing a web application I want to perform certain validation check and only after sucesssful validation I need to post the form and redirect control to next page.
JavaScript code:
function fnCheckEmptyField()
{
var strDomain = document.getElementsByName("txtIIDN").value;
if (strDomain == null)
{
document.getElementById("lblValidityStatus").innerHTML = "";
document.getElementById("lblValidityStatus").innerHTML = "Domain Name Field Can't be Left Blank";
return false;
}
else
{
return true;
}
}
Relevant HTML code:
<form action="Result.jsp" name="validityCheck" onsubmit="return fnCheckEmptyField()">
<input type="text" id="txtIIDN"/>
<input type="submit" id="btnValidityCheck" value="Check Validity" />
</form>
The line onsubmit="return fnCheckEmptyField()" shows an error Cannot return from outside a function or method and after execution of the JavaScript function form is getting submitted regardless the text field is blank or not.
I have placed alerts inside if condition and it is sure that if field is empty function returns false.
I don't know what's wrong with my code and why this errors with Cannot return from outside a function or method.
What's the cause and how can I solve it?
the line onsubmit="return fnCheckEmptyField()" showing an error Cannot return from outside a function or method
That's specific to Eclipse. Eclipse is wrong here, that line is perfectly fine. Just ignore the Eclipse error. If you want, you can always disable its JS validation.
and after execution of the java script function form is getting submitted regardless the text field is blank or not.
That's because your JavaScript function is wrong. You've 2 mistakes in your JS code.
The getElementsByName() call is incorrect.
var strDomain = document.getElementsByName("txtIIDN").value;
To retrieve an element by ID, you need getElementById().
var strDomain = document.getElementById("txtIIDN").value;
Empty values are not null, but just empty string.
if (strDomain == null)
You need to check its length instead.
if (strDomain.length == 0)
Or just make use of JS boolean magic.
if (!strDomain)
By the way, the line document.getElementById("lblValidityStatus").innerHTML = ""; is unnecessary in this code.
remove the "return" from onsubmit attribut
your code should look like this
<form action="Result.jsp" name="validityCheck" onsubmit="fnCheckEmptyField()">
<input type="text" id="txtIIDN"/>
</form>
hope this solve your problem :-)
Also,
var strDomain= document.getElementsByName("txtIIDN").value;
should be
var strDomain= document.getElementById("txtIIDN").value;
The text field has an id, not a name
Remove Action from Form Tag.
function fnCheckEmptyField()
{
var strDomain= document.getElementsByName("txtIIDN").value;
if(strDomain == null)
{
document.getElementById("lblValidityStatus").innerHTML="";
document.getElementById("lblValidityStatus").innerHTML="Domain Name Field Can't be Left Blank";
}
else
{
window.navigate("top.jsp");
}
}
I'm no javascript expert but I think you should lose the return keyword in your onsubmit parameter in the HTML; like below:
onsubmit="fnCheckEmptyField()"
edit: sorry was posting concurrently with previous answer

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

Displaying Message near TextBox using Javascript

I am having an aspx form and in that i need to do validations using jquery or javascript.
I just want to give a message near to the textbox if a user enter a value which is not valid in that textbox.Inorder to display the message in a popup [not alert('message')]
How can I find the position of the textbox in which user enters the invalid data or how can i display a message near the textbox using javascript or jquery ?
I need the validation occur in blur.So it is easy for user to know whether he entered a valid data immediately after giving the input.
Thanks in advance.I am not interested to use asp.net ajax validation and its callout extender.
I just want to implement a functionality which is similar to validation callout extender does.
When you bind the blur event to the textbox, you know which textbox it is. Just use your callback javascript to insert the error near by.
If you're doing jquery, it might look something like:
$('.my_textboxes').blur(function() {
var textbox = $(this);
//ajax validation call
$.post('/whereever', {}, function(response) {
//ajax callback
if (response == 'error') {
textbox.next().html(error); //something like this to insert the error into the next element after the texrbox, eg, a span to hold the error
}
});`
You can use the jQuery (ASP.NET) Validator Callout Plugin
You can use the jQuery validation plugin
http://ajax.microsoft.com/ajax/jquery.validate/1.7/jquery.validate.js
http://ajax.microsoft.com/ajax/jquery.validate/1.7/jquery.validate.min.js
http://ajax.microsoft.com/ajax/jquery.validate/1.7/jquery.validate.pack.js
http://ajax.microsoft.com/ajax/jquery.validate/1.7/additional-methods.js
Which has options to specify the message beside the control or to specify all the message at one place.
The demos are available at
http://docs.jquery.com/Plugins/validation
Exactly how you do this depends on the layout of your form, but in general you probably would do something like this: if the validation returns an error for a text field, check to see if an "error box" already exists for that field. If so, then just update its contents with the new error message; if not, then add the error element.
One way to do that would be to use a <span> tag with a particular class (for layout purposes), and an "id" value made from the input field's "name" or "id":
$.fn.setValidationResult = function(errorMessage) {
return this.each(function() {
var errId = 'errMsg_' + this.name, errMsg = $('#' + errId);
if (!errMsg.length) {
$(this).after($('<span></span>', { class: 'validation-error', id: errId }));
errMsg = $('#' + errId);
}
if (errorMessage)
errMsg.html(errorMessage).show();
else
errMsg.html('').hide();
});
});
Then you can just use $(yourInput).setValidationResult(whatever); with "whatever" being empty when validation passes.

Categories