I am using custom function for validating my input on edit. Following is the piece of code.
editrules:{custom: true, custom_func: customValidation}
function customValidation(val, colname) {
if (val.trim() == "") {
return [ false,"name is required " ];
} else {
return [ true, "" ];
}
}
This works fine and it displays an alert if the validation is false. I want to display my custom alert box.
I tried to use my custom alert box like
showCustomBox('ERROR', 'Name is required! ',{title : 'Error: Edit xxx grid'});
// where the function param means showCustomBox(type, message, heading);
return[false, ""];
But this displays my alert as well as the default alert. Is there a way to use oly custom alert during return? Pls suggest. Thanks in advance.
jqGrid don't provide any direct way to customize validation dialog. Nevertheless one can do make some tricks to implement what you need.
First of all one have to examine how jqGrid implements custom validation. jqGrid calls $.jgrid.checkValues to validate the input data. The method $.jgrid.checkValues calls custom_func if required (see here). Then jqGrid calls here $.jgrid.info_dialog method to display the error message. So one can for example subclass the $.jgrid.info_dialog method to display custom error message in the way like I described in the answer.
I made the demo which demonstrates the approach. The demo have custom validation in "name" column. The validation require that the saved value have to start with the text "test". I used alert to display the custom error message. Below is the main parts of the code which I used in the demo:
var useCustomDialog = false, oldInfoDialog = $.jgrid.info_dialog;
...
$.extend($.jgrid,{
info_dialog: function (caption, content, c_b, modalopt) {
if (useCustomDialog) {
// display custom dialog
useCustomDialog = false;
alert("ERROR: " + content);
} else {
return oldInfoDialog.apply (this, arguments);
}
}
});
...
$("#list").jqGrid({
...
colModel: [
{ name: "name", width: 65, editrules: {
custom: true,
custom_func: function (val, nm, valref) {
if (val.slice(0, val.length) === "test") {
return [true];
} else {
useCustomDialog = true; // use custom info_dialog!
return [false, "The name have to start with 'test' text!"];
}
} } },
...
],
...
});
As the result jqGrid could display the error message like below if one would try to save the data for "Clients" ("name") column which text don't start with "test" text
Related
I have the following code:
var students = new Bloodhound({
datumTokenizer: Bloodhound.tokenizers.obj.whitespace('fullName'),
queryTokenizer: Bloodhound.tokenizers.whitespace,
remote: {
url: '/api/students?query=%QUERY',
wildcard: '%QUERY'
}
});
$('#student').typeahead({
minLength: 2,
highlight: true,
},
{
name: 'students',
display: function (item) { return item.fullName },
source: students.ttAdapter(),
templates: {
empty: [
'<div class="tt-empty-message">' +
'No results found' +
'</div>'
]
}
}).on("typeahead:select",
function (e, student) {
console.log("inside isselect");
isSelected = true;
vm.studentId = student.id;
});
I am trying to capture a scenario where if a user enters some gibberish or something apart from typeahead values and clicks on submit button, then I need to display an error message. To do that, I need to capture the typeahead list and see if the typeeahed list contains the input value. How can I accomplish this?
I have searched for this solution for 5 hours now. I have looked and implemented similar answers on other threads but nothing seemed to work. For instance take a look at this answer:
http://jsfiddle.net/Fresh/bbzt9hcr/
I tried the baove code but the typeahed does not even come up. Whereas my code works perfectly fine. Please let me know how I can solve this. Thank you in advance.
There are multiple way to approach this, the simplest:
you could listen the typeahead change event and use a variable to store the selected value, then on submit check and send that variable: http://jsfiddle.net/alfredopacino/bbzt9hcr/290/ .
yourTypehead.on('typeahead:selected', function($e, datum) { // suggestion selected
selectedMovie = datum.value
});
$('#submit').click(function() {
if(selectedMovie) {
//your ajax call
} else {
alert("no valid movie")
}
});
The problem with this is it doesn't covers the case the user enters manually a valid value.
To cover this scenario you could follow two ways:
onSubmit you can add a 'remote validation': basically an additional ajax request to check if the value is valid using the server
convert your typeahead selection in a "tag selection", limit the tags to 1 and forbid any custom value https://bootstrap-tagsinput.github.io/bootstrap-tagsinput/examples/ (there are TONS of plugin doing that)
I have a CKEDITOR plugin that I'm having trouble disabling when there is no selected copy in the editor. Right now, the user can click the button without any highlighted text in the editor. I would like to modify it so that the plugin button is only active when there is copy highlighted in the editor. I've followed the suggestion here, but it isn't working.
Main Plugin Code:
CKEDITOR.plugins.add('cta', {
icons: 'cta',
init: function (editor) {
// Funciton depending on editor selection (taken from the scope) will set the state of our command.
function RefreshState() {
console.log('RefreshState');
var editable = editor.editable(),
// Command that we want to control.
command = editor.getCommand('source'),
range,
commandState;
if (!editable) {
// It might be a case that editable is not yet ready.
console.log("editable not ready yet");
return;
}
// We assume only one range.
range = editable.getDocument().getSelection().getRanges()[0];
console.log(`range: `);
console.log(range);
// The state we're about to set for the command.
commandState = (range && !range.collapsed) ? CKEDITOR.TRISTATE_OFF : CKEDITOR.TRISTATE_DISABLED;
console.log('commandState');
console.log(commandState);
command.setState(commandState);
}
// We'll use throttled function calls, because this event can be fired very, very frequently.
var throttledFunction = CKEDITOR.tools.eventsBuffer(250, RefreshState);
// Now this is the event that detects all the selection changes.
editor.on('selectionCheck', throttledFunction.input);
// You'll most likely also want to execute this function as soon as editor is ready.
editor.on('instanceReady', function (evt) {
// Also do state refresh on instanceReady.
RefreshState();
});
editor.addCommand('ctabtn', new CKEDITOR.dialogCommand('ctaDialog'));
editor.ui.addButton('cta', {
label: 'Insert Call to Action button',
command: 'ctabtn',
toolbar: 'insert'
});
CKEDITOR.dialog.add('ctaDialog', this.path + 'dialogs/cta.js');
}
});
My dialog code is here:
CKEDITOR.dialog.add('ctaDialog', function (editor) {
return {
// Basic properties of the dialog window: title, minimum size.
title: 'Call to Action',
minWidth: 400,
minHeight: 200,
// Dialog window content definition.
contents: [{
// Definition of the Basic Settings dialog tab (page).
id: 'tab-basic',
label: 'Basic Settings',
// The tab content.
elements: [{
// Text input field for the Call to Action text.
type: 'text',
id: 'cta',
label: 'Call to Action',
// Validation checking whether the field is not empty.
validate: CKEDITOR.dialog.validate.notEmpty("Call to Action field cannot be empty.")
},
{
// Text input field for the link text.
type: 'text',
id: 'url',
label: 'URL',
// Validation checking whether the field is not empty.
validate: CKEDITOR.dialog.validate.notEmpty("URL field cannot be empty.")
}
]
}],
// method invoked when the dialog button is clicked
onShow: function () {
var element = editor.getSelection();
var link = CKEDITOR.plugins.link;
var _this = this.getParentEditor();
var CTAhref = link.getSelectedLink(_this);
this.setValueOf('tab-basic', 'cta', element.getSelectedText().toString());
if (CTAhref != '' && CTAhref !== null) {
this.setValueOf('tab-basic', 'url', CTAhref.$.href);
}
},
// This method is invoked once a user clicks the OK button, confirming the dialog.
onOk: function () {
var dialog = this;
var CTA = editor.document.createElement('a');
CTA.setAttribute('href', dialog.getValueOf('tab-basic', 'url'));
CTA.setAttribute('class', 'btn btn-special--lg');
CTA.setText(dialog.getValueOf('tab-basic', 'cta'));
editor.insertElement(CTA);
}
};
});
Any ideas on why the plugin icon button on the toolbar doesn't become inactive when there is no copy highlighted in the editor? I can see in the console that CKEDITOR.dom.range.collapsed is toggling between TRUE/FALSE depending upon whether text is highlighted or not. It's just not disabling the button.
As stated, the suggested way of handling this was not working for me. What was working was using range.collapsed in returning a true value if a selection was made in the editor. With that, I turned to using Jquery to handle the rest.
// Hacky. But it gets the job done.
// a.cke_button.cke_button__cta.cke_button_off is the selector for my toolbar button.
// The onclick function listed was pulled from looking at the CKeditor functions
// to initiate my plugins modal.
// The setting of the "onclick" prop to null is needed to override the modal onclick
// binding when there is no selection.
range = editable.getDocument().getSelection().getRanges()[0];
if (range.collapsed === false) {
$('a.cke_button.cke_button__cta.cke_button_off').attr("onclick", 'CKEDITOR.tools.callFunction(83,this);return false;');
$('a.cke_button__cta').toggleClass('cta_button_disabled');
} else {
$('a.cke_button.cke_button__cta.cke_button_off').prop("onclick", null);
}
I have two validations for the same field and I´m using jQuery Validator, I would like to know how to clean the previous error message generated.
My problem now is that If I have the error for empty field, never is removed if I have another error like value must be higher than 10. I still showing "field must not be empty" when the value is 7.
I google on that and all suggestion are resetForm of validation.
var validator = $("#myform").validate(
);
validator.resetForm();
But of course if I do that the error message wont be showed. I just need to clean the previous error from the DOM before check for news.
Anyone knows another approach directly interacting with the DOM?
I´m trying this without success.
if ($.validator.defaults.onfocusout) {
$(element).unbind(".validate-biggerThanOrigin").bind("blur.validate-biggerThanOrigin", function () {
$(element).valid();
});
}
We´re defining the validation like this.
$.validator.addMethod("biggerThanOrigin", function (value, element, param) {
return biggerThanOrigin(value, element, param, validationMessages.biggerThanOrigin, validationMessages.referenceForkEmpty);
});
$.validator.addMethod("lessThanOrigin", function (value, element, param) {
return lessThanOrigin(value, element, param, validationMessages.lessThanOrigin, validationMessages.referenceForkEmpty);
});
Regards.
You should provide separate validation messages for errors.
$("#myform").validate({
rules: {
name: {
"required": true,
"minlength": 10
},
messages: {
name: {
required: "Please specify your name",
minlength: "Your name must be atleast 10 characters long"
}
}
});
This should work in your case.
EDIT:
Here is a working FIDDLE.
As you asked another approach , so here is the solution.
FIDDLE:
$('input').on('keyup', function () {
if ($(this).val().length == 0)
$('label').text('Field must not be empty');
else if ($(this).val() <= 10)
$('label').text('Value must be greater than 10');
else
$('label').text('');
});
This is just an example. You can use the approach.
Thanks anyway !
I am having some trouble with getting the JQueryUI Tooltip Widget working with parsley validation. This is my code:
$.listen('parsley:field:error', function (fieldInstance) {
var messages = ParsleyUI.getErrorsMessages(fieldInstance);
if(fieldInstance.$element.tooltip('instance') != undefined) {
fieldInstance.$element.tooltip('destroy');
}
fieldInstance.$element.tooltip({
items: fieldInstance.$element,
content: messages,
show: 'pulsate'
});
fieldInstance.$element.tooltip('show');
});
My methology is:
Check if a tooltip exists (as multiple validation occur), if it does destroy it.
Create the tooltip with the appropriate message
Show the tooltip
But I just get a consol error:
Uncaught Error: no such method 'show' for tooltip widget instance
Also, if anyone thinks there is a better way of doing this please don't hesitate to answer!
You have a few issues with your code:
The main issue is that you're calling .tooltip('show'); but there is no such method or event, according to the API documentation. You have to use .tooltip('open').
The content option accepts a function or string and you're passing an array. You need to implode the messages array with something like messages.join('<br />')
In order to show the errors only within the tooltip, you need to change the default options of parlsey, specifically errorsContainer and errorsWrapper.
Your final code will be something like this (test in this jsfiddle):
$(document).ready(function() {
$("#myForm").parsley({
errorsContainer: function (ParsleyField) {
return ParsleyField.$element.attr("title");
},
errorsWrapper: false
});
$.listen('parsley:field:error', function (fieldInstance) {
var messages = ParsleyUI.getErrorsMessages(fieldInstance);
if(fieldInstance.$element.tooltip('instance') != undefined) {
fieldInstance.$element.tooltip('destroy');
}
fieldInstance.$element.tooltip({
content: messages.join('<br />'),
items: fieldInstance.$element,
show: 'pulsate'
});
fieldInstance.$element.tooltip('open');
});
});
I currently use Jquery Validation and Qtip together to deal with the actual validation and displaying of information to the screen using the nice tooltip style notifications upon validation errors using the errorPlacement component of the validation options.
Currently each viewModel has its own custom method for setting up and kicking off the validation and callbacks, however I was trying to look at a nicer way of doing this, be it adding a custom binding to setup my validation rules via the data-bindings or an alternative way, but still yielding the same results (i.e the errorPlacement is triggered when a validation error occurs and tells Qtip to display the error for the given element).
Now before I started making one myself I just checked online and found Knockout Validation, which I initially thought was a great idea, I could apply my validation logic directly to the data within my viewModel and then just find some sort of callback to get Qtip to kick in, however it seems there is no callback that I can find documented. The library seems to do everything I want for the validation side of things, just not for the displaying side of things. I looked through the source code and examples but couldn't see anything other than ko.validation.group(viewModel) which would give me an observable containing the errors, but I am not sure if I could use this the same way as I was expecting.
Here is an example of how my current validation happens:
/*globals $ ko */
function SomeViewModel() {
this.SetupValidation = function () {
var formValidationOptions = {
submitHandler: self.DoSomethingWhenValid,
success: $.noop,
errorPlacement: function (error, element) {
if (!error.is(':empty'))
{ qtip.DoSomethingToDisplayValidationErrorForElement(element, error); }
else
{ qtip.DoSomethingToHideValidationErrorForElement(element); }
}
};
$(someForm).validate(formValidationOptions);
this.SetupValidationRules();
};
this.SetupValidationRules = function() {
$(someFormElement1).rules("add", { required: true, minlength: 6, maxlength: 20, alphaNumeric: true });
$(someFormElement2).rules("add", { required: true, minlength: 6, maxlength: 20 });
$(someFormElement3).rules("add", { required: true, email: true, });
};
}
I currently am sure I can remove the need for the validation rules method by adding a custom binding so I can set the validation in the data-bind, however if possible I would like to use the same sort of callback approach with the existing Knockout-Validation binding.
I haven't used Knockout-Validation specifically but I have written something similar in the past. A quick glance at the source shows that each extended observable gets a sub-observable isValid. This could be used to hide show messages in your markup using conventional knockout visible bindings.
To get QTip to work a custom binding could subscribe to this isValid property and perform the necessary initialization to show/hide QTip when triggered.
EDIT
Here is an example to get you started
http://jsfiddle.net/madcapnmckay/hfcj7/
HTML:
<!-- Note that you have to reference the "qtipValMessage" binding -->
<!-- using the "value" binding alone is not enough -->
<input data-bind="value: emailAddress, qtipValMessage : emailAddress" />
JS:
ko.bindingHandlers.qtipValMessage = {
init: function (element, valueAccessor, allBindingsAccessor, viewModel) {
var observable = valueAccessor(), $element = $(element);
if (observable.isValid) {
observable.isValid.subscribe(function(valid) {
if (!valid) {
$element.qtip({
overwrite: true,
content: {
text: observable.error
}
});
} else {
$element.qtip("destroy");
}
});
}
}
};
I had been editing madcapnmckay's post, but the differences have become significant enough that I think a new answer is needed.
It is heavily based off of madcapnmckay's post, but it fixes a bug pointed out by MorganTiley. The original only works if the user has modified the observable. If they haven't then the code never gets fired. So, I've modified it so that it fires the tooltip code when it gets created, in addition to when it changes.
ko.bindingHandlers.qtipValMessage = {
init: function (element, valueAccessor, allBindingsAccessor, viewModel) {
var observable = valueAccessor(), $element = $(element);
if (observable.isValid) {
var updateTooltip = function (valid) {
if (!valid) {
$element.qtip({
overwrite: true,
content: {
text: observable.error
}
});
} else {
$element.qtip("destroy");
}
}
updateTooltip();
observable.isValid.subscribe(updateTooltip);
}
}
};
The one downside is that the tooltip will display on hover before knockout validation has been run (example, you have a "required" validation on a field, before you press submit a tooltip will display saying the field is required, but the field will not highlight in pink). Once you change the field however, the tooltip will disappear if the field is valid.
My app was not using qtip, but rather Twitter Bootstrap Tooltip, so here is the code for that as well.
ko.bindingHandlers.invalidTooltip = {
init: function (element, valueAccessor, allBindingsAccessor, viewModel) {
var observable = valueAccessor(), $element = $(element);
if (observable.isValid) {
var updateTooltip = function (valid) {
if (!valid) {
$element.attr("data-original-title", observable.error);
$element.tooltip();
} else {
$element.tooltip("destroy");
}
}
updateTooltip();
observable.isValid.subscribe(updateTooltip);
}
}
};