How to configure custom validation rules for kendo grid editor - kendo-grid

We have ASP.NET MVC application using Telerik UI for ASP.NET MVC. On the page is set up a grid with popup editor, by kendo html helper.
Now I need to configure some custom validation rules for popup editor form. I can't find a way how to do it.
In validator documentation can be seen to get validator reference from $("form"). But there is no form in grid popup
If I configure rules on validator taken from $("gridName").kendoValidator().data("kendoValidator"), such rules are simply not fired when saving editor changes
If I get reference to validator from some editor container gridOnEditEvent.container.find("#editorcontent").kendoValidator().data("kendoValidator"), for example, I can extend rules, validate and send form data manually, but standard save button of the popup editor doesn't reflect such configuration
How can extend validation rules of the grid popup editor validator?

Kendo widgets built with an HTML helper, such as the Grid, initialize their own internal Validator. Custom rules must be added to the Validator class itself in order to run in these inaccessible instances of the Validator. Telerik has an example of how to do this:
$.extend(true, kendo.ui.validator, {
rules: { // custom rules
productnamevalidation: function(input, params) {
if (input.is("[name='ProductName']") && input.val() != "") {
input.attr("data-productnamevalidation-msg", "Product Name should start with capital letter");
return /^[A-Z]/.test(input.val());
}
return true;
}
},
messages: { //custom rules messages
productnamevalidation: function(input) {
// return the message text
return input.attr("data-val-productnamevalidation");
}
}
});

Related

TinyMCE <p> </p><div id="ConnectiveDocSignExtentionInstalled" data-extension-version="1.0.4"></div>

I have a MultiLine TextField in ASP.net VB with TinyMCE. A user of our website has a plugin on his computers that insert unwanted HTML code into the TinyMCE TextField.
<p> </p><div id="ConnectiveDocSignExtentionInstalled" data-extension-version="1.0.4"></div>
Is there a way to filter this text and remove it before saving the full textfield content to my SQL database?
One option is to use a TinyMCE node filter to remove the element when it serializes the content inside the editor. Here's an example:
setup: (editor) => {
editor.on('PreInit',() => {
// Create a custom node filter to remove unwanted content when getting content from the editor
editor.serializer.addNodeFilter('div', (nodes) => {
nodes.forEach((node) => {
const id = node.attr('id');
if (id === 'ConnectiveDocSignExtentionInstalled') {
node.remove();
}
});
});
});
}
and a working version of it: https://fiddle.tiny.cloud/RAhaab/1
This works by registering a filter during the initialization sequence to remove the offending div added by the users extension when TinyMCE fetches the content from the editor. More information about the Node API used by the filter can be found here: https://www.tiny.cloud/docs/api/tinymce.html/tinymce.html.node/
Another option, that would depend on your integration, is to use server-side filtering of the content sent. How you do that would differ based on the frameworks, etc... being used.
Came here just to say that this extra code is entered into text areas that process HTML when you have the "Connective Signing Extension" installed.
This extension gets installed when you use an electronic European ID card to log into government or banking services in the EU.
Today, I found their website and reported this behavior via their contact form.
I hope they respond, but I recommend others experiencing the same behavior please contact them and bubble up the bug!

custom web component form element for constraint validation

Only some HTMLElements support the constraint validation api (e.g., HTMLButtonElement). I want to create a custom web component, which also supports the constraint validation api.
In the following an example is given for the desired outcome:
<form>
<input name="title" required>
<custom-form-component></custom-form-component>
</form>
<script>
const form = document.querySelector('form');
form.checkValidity();
</script>
The custom-form-component could call setCustomValidity on itself (based on the respective user input context) and validate itself true or false. Thus, the call on the form.checkValidity() should return true or false with respect to the outcome of the custom-form-component.
As I found from documentaion (e.g. on MDN) only for some element it is possible to attach a shadow root. It is not possible for form elements. However, only form elements suport the constraint validation api.
concrete question:
How can I realise a custom web component, which supports constraint validation api?
This is a new introduction to Web Components. As of Sept 25, 2019 only Chrome 76 supports it.
Here is an article provided by Google Web Devs:
https://web.dev/more-capable-form-controls/
It talks about the various additions to Web Components that let them properly integrate as a form element.
This includes:
Form validation
The :disabled, :invalid and :valid CSS pseudoclasses
The formdata event
And a static formAssociated property that tells the browser to treat your element like a form control.
Plus several other things that allows your control to function correction in a <form>

How can I validate on the client if I use MVC validation but posting a JSON object?

I'm developing a ASP.NET Core web application where I'm using DataAnnotations to decorate my view model with validation attributes. When I open a detail page with my inputs, I see that Core added the HTML5 validation attributes to the rendered HTML (i.e. data-val="true").
However, I wrote custom client-side code when the user clicks on the Save button like this:
$(document).on("click", "#SaveAsset", function (event) {
event.preventDefault();
Asset.Save();
});
I also have a Save function defined like this:
window.Asset.Save = function () {
var postData = {
'Id': $("#Id").val(),
'SerialNumber': $("#SerialNumber").val(),
'PartNumber': $("#PartNumber").val(),
'assetTypeId': $("#AssetTypeId").val()
};
$.post('/Asset/SaveAsset', postData);
}
I need to validate on the client side first before calling $.post but I'm confused about how to do it. Microsoft shows that the unobtrusive javascript works automatically when you use it with forms. But I'm not using the HTML form element to submit my page. So how can I trigger the HTML5 validation attributes?
I added the links to jquery.validate.js and jquery.validate.unobtrusive.js. Right now, if I click the Save button the data is sent to the server and the controller checks the ModelState. But it shouldn't even be sending anything to the server. The client should stop the validation.
Should I even stop doing it this way? For example, creating my postData JSON object by getting the val() of each input.
Should I use the form element? I stopped using it because my page has hundreds of inputs so I was worried I would have problems. This way, I have control over each input.
Use a javascript solution like jQuery Validation Plugin to validate data before sending to the server. Otherwise, send the data to the server, and return a the errors with a bad request if validation fails.
Eg.
Return BadRequest(string[]{"Name is required", "Id must me a number"});
then capture the errors and shoe to the user

Alternative Ways to Do Site-specific Rich Text Editor CSS?

I've been wanting to implement site-specific rich text css classes but have come onto an issue. I can't change anything global in this environment. The tutorials require me to change an EditorPage.aspx file. I am not able to do this. Is there any other way to set up site specific css classes for the rich text editor?
I'm on Sitecore 7.5.
Thanks!
This is very similar to a previous Stackoverflow question which I answered about Multtiple RTE Class Styles, which I followed up with a blog post which includes details about loading site specific css styles in Sitecore rich text editor.
Create a new EditorConfiguration class inheriting from Sitecore.Shell.Controls.RichTextEditor.EditorConfiguration and override the SetupStylesheets() method. Then register that new Configuration Type in the 'core' database against your HTML Editor Profile, then set the source of the RTE field in your template to your to your Rich Text Profile.
In your SetupStylesheets() method you need to use an xpath query to get the list of site specific css files:
protected override void SetupStylesheets()
{
string id = WebUtil.GetQueryString("id");
string query = "/*/content//*[##id='" +id+ "']/ancestor::*[##templateid='{root-guid}']//*[##templateid='{style-folder-guid}']/*";
IList<Item> stylesheets = Sitecore.Context.ContentDatabase.SelectItems(query);
foreach (Item item in stylesheets)
{
this.Editor.CssFiles.Add(item["Stylesheet"]);
}
base.SetupStylesheets();
}

ASP.NET MVC Redirect with Form inside IFrame

I am developing a SharePoint app that is using an ASP.Net MVC web application. The web application is launched inside an iframe in SharePoint.
I have a form that I use to store information related to a project. Different actions are possible on this form:
Submit form with no error: the form is redirected to the homepage of my project. For that I am using.:
Html.BeginForm(.., FormMethod.Post, new { **#target="_top**", #class = "form-horizontal" })
As you can see i redirect my form to the target _top to be able to go back to my homepage.
Cancel form: the form is cancelled and i am redirected to the homepage of my project. For that I am using also a link with the target _top:
Cancel:
Everything is working for this case
Submit form but error in the post method:
now let's imagine that i submit my form but i have some error during processing. What I would like to do is to display again the form inside my frame in my page with the validation error present on the top of the form.
The problem is explain above, my form has the target set to top, the validation errors are displayed on the top windows and not in my frame. So it is like that I am redirected to a new page.
Here is the code my post action:
if (!ModelState.IsValid)
{
return View("Edit", KeyFiguresHelper.BuildKeyFiguresEditViewModel(keyFigure, agencies));
}
var keyFiguresDTO = KeyFiguresHelper.ExtractKeyFiguresFromModel(model, agencies);
var errorCode = _projectService.EditProjectKeyFigures(keyFiguresDTO);
if (errorCode == ErrorCode.NO_ERROR)
{
return Redirect(keyFigure.ProjectUrl);
}
ModelState.AddModelError("", _errorMessageFactoryService.Create(errorCode));
return View("Edit", KeyFiguresHelper.BuildKeyFiguresEditViewModel(keyFigure, agencies));
Is it possible to redirect a page with the target "_top" if the post action is running well and if I have any errors to redirect to the same page with the target "_self" ?
Thank you very much for your help