how to validate selectize dropdownlist in mvc 4.5? - c#

I am working with mvc in framework-4.5. In all other fields validation is working properly, but i am finding it difficult for selectize dropdownlist. Validation is working properly in simple dropdownlist also.
I tried to show message using field-validation-error and input-validation-error but not getting any success. Here are some changes i made in jquery.validate.unobtrusive.js.
function onError(error, inputElement) { // 'this' is the form element
var container = $(this).find("[data-valmsg-for='" + escapeAttributeValue(inputElement[0].name) + "']"),
replaceAttrValue = container.attr("data-valmsg-replace"),
replace = replaceAttrValue ? $.parseJSON(replaceAttrValue) !== false : null;
container.removeClass("field-validation-valid").addClass("field-validation-error");
error.data("unobtrusiveContainer", container);
if (replace) {
container.empty();
error.removeClass("input-validation-error-+-").appendTo(container);
}
else {
error.hide();
}
//For Validation Toggel Start
debugger;
if ($(inputElement).parent().hasClass("selectize-input")) {
$(inputElement).parent().parent().parent().addClass("md-input-danger");
var container = error.data("unobtrusiveContainer");
container.removeClass("field-validation-valid").addClass("field-validation-error");
}
}
I did lots of research for this but i didn't get any proper solution.
please help me to solve this issue.
Thanks

add below JQuery code in document ready to validate your selectize dropdown
$.validator.setDefaults({
ignore: ':hidden:not([class~=selectized]),:hidden > .selectized, .selectize-control .selectize-input input'
});

Related

How to prevent textbox from copying letters into that?

I am currently working on a C# MVC project. While entering user details into database I need to customize my MobilePhone field to only accept numbers. After some searching I found the below code :
$(document).on("keypress","#MobilePhone", function (e) {
var regex = new RegExp("^[0-9]\d*$");
var str = String.fromCharCode(!e.charCode ? e.which : e.charCode);
if (regex.test(str)) {
return true;
}
e.preventDefault();
return false;
});
This code works for me, It only allows numbers to be entered in the Textbox.
But there is a problem, If a user copy some text and then paste the content in the Textbox nothing happens. Then if I press submitt button it submits and occur error.
So then I found this question :Disable Copy or Paste action for text box?
Answer to the question is :
$('#email').bind("cut copy paste",function(e) {
e.preventDefault();
});
But after I tried this I can not copy even numbers to the textbox. Is there any way I can prevent copying of alphabets and special characters only.
Just add some checks in your binding to prevent cut / copy / paste a non-number : https://jsfiddle.net/hswtutd9/
$(function() {
$("#email").bind("cut copy paste", function(e) {
const data = e.originalEvent.clipboardData.getData("Text")
if(! /\d./.test(data)) {
e.preventDefault()
}
})
})
why are you using text as your input type ????
if you are using strongly typed view ie editor for then just use data annotation
[DataType(DataType.PhoneNumber)]
public string PhoneNumber{get;set;} //i've used string here believing you initially made it as string and hence not effecting the code elsewhere
if you are using html inputs try
input type ="tel" note some brawser does not support tel for them i would prefer number
You can put the phone number validation code in a function and call if both places like:
function IsValidPhoneNumber(number) {
var regex = new RegExp("^[0-9]\d*$");
if (regex.test(number)) {
return true;
}
return false;
}
and now you can call it both places like:
$(document).on("keypress","#MobilePhone", function (e) {
if(!IsValidPhoneNumber($(this).val())) {
e.preventDefault();
return false;
}
}
$('#MobilePhone').bind("cut copy paste",function(e) {
if(!IsValidPhoneNumber($(this).val())) {
e.preventDefault();
return false;
}
});
or more better would be in a single event:
$(document).on("cut copy paste keypress","#MobilePhone", function (e) {
if(!IsValidPhoneNumber($(this).val())) {
e.preventDefault();
return false;
}
}
Now it would allow copying if the value satisfies the regular expression, you might need to tweak the function to check the whole number but this should give you idea how you can allow it there.
Hope it helped!

kendo treeview mvc - error when clicking node

I'm getting an error within the kendo.all.min.js when I try and click on one of the nodes in a TreeView - anyone know if I have to further configure it to avoid this?
The error I'm getting is:
JavaScript runtime error: Unable to get property 'set' of undefined or null reference
and the rough area that is highlighted on error by VS is:
return arguments.length?(n=e(n,r).closest(q),r.find(".k-state-selected").each(function(){var e=i.dataItem(this);e.set("selected",!1),delete e.selected}),n.length&&i.dataItem(n).set("selected",!0)...
What i'm after is basically a list of files within a parent folder, and if the file is active and has child files, then I'd like it to give it a URL so they can open the link, but if not, I'd like nothing to happen, but I don't want to completely disable the node as I'd like the user to be able to expand it or shrink it if required.
Here is the code I'm using for the treeview in MVC:
#(Html.Kendo().TreeView()
.Name("treeview")
.Items(level1 =>
{
level1.Add().Text(rootFolderName)
.SpriteCssClasses("folder")
.Expanded(true)
.Items(level2 =>
{
int count = 0;
foreach (var node in list)
{
string title = node.Title;
string url = "";
if (node.HasChildren)
{
title = node.Title + "(" + node.ChildrenCount + ")";
url = "/Secure/Areas/Compliance.aspx?id=" + node.ItemId;
}
level2.Add().Text(title).Url(url)
.Expanded(true);
}
});
})
)
Anyone used these before and know what else I'm needing to do to achieve my aim?
Ok, learning more as I go. Ended up using an event like so:
#(Html.Kendo().TreeView()
.Name("treeview")
.Events(events => events
.Select("onSelect")
)
.Items(level1 =>
and then added a preventDefault if the url is empty
function onSelect(e) {
var dataItem = $('#treeview').data('kendoTreeView').dataItem(e.node);
if (dataItem.href == 'undefined')
e.preventDefault();
else
location.href = dataItem.href;
}
There is maybe a better way, but this seems to work so I'm happy for now.

How to maintain/access textbox values across postbacks which are set by Javascript/Jquery?

I am looking for a way to maintain the GridView TextBox values which are set by jQuery across postbacks. I searched a lot on Google but could not find a solution.
function CalculateTaxes() {
var taxvaluesum = 0;
$(".taxvalue").each(function () {
//add only if the value is number
if (!isNaN(this.value) && this.value.length != 0) {
taxvaluesum += parseFloat(this.value);
}
else {
$(this).val('0')
}
});
//$('.totaltaxvalue').val(taxvaluesum.toFixed(2));
$('.totaltaxvalue').attr("value", taxvaluesum.toFixed(2));
var finalamt = parseFloat($('.totaltaxvalue').val()) + parseFloat($('#ContentPlaceHolder1_Gridview1_txtftrvalue').val());
$('.finalamount').attr("value", finalamt.toFixed(2));
//$('.finalamount').val(finalamt.toFixed(2));
}
$(document).on('blur', ".taxvalue", function (e) {
CalculateTaxes();
var roundedvalue =parseFloat($(this).val()).toFixed(2);
$(this).val(roundedvalue);
$(this).siblings('input[type="hidden"]').val(roundedvalue);
alert($(this).siblings('input[type="hidden"]').val());
});
I once faced similar issue, retrieving value directly like hdnElement.Value was always empty on post back. The below worked for me.
Request.Form(hdnElement.UniqueID))

Regular Expression to avoid HTML tags and empty values

I have applied a textbox click validation and wanted to avoid any html tags in text box also the simple < (open tag) and >(close tag). The below code is working for but i want to add additional validations also for empty strings and other tags in html. Can some one please help modify the regex for the requirement.
function htmlValidation()
{
var re = /(<([^>]+)>)/gi;
if (document.getElementById(’<%=TextBox2.ClientID%>’).value.match(re)){ document.getElementById(’<%=TextBox2.ClientID%>’).value = “”;
return false;
}
return true;
}
Corrected Code above
In my opinion, I believe you'll have a good hard work if you want to validate such things.
Instead of preventing HTML content in a text box, other solution could be just html entity encode Text property, so <p>a</p> would be converted to >p<a>p<.
Result of that is you're going to render the HTML "as text" instead of getting it interpreted by Web browser.
Check this MSDN article:
http://msdn.microsoft.com/en-us/library/73z22y6h(v=vs.110).aspx
$("#<%= btnAdd.ClientID %>").click(function () {
var txt = $("#<%= txtBox1.ClientID %>");
var svc = $(txt).val(); //Its Let you know the textbox's value
var re = /(<([^>]+)>)/gi;
if(txt.val()!=""){
if (!txt.val().match(re)) {
//my Operations
//goes here
});
return false;
}
else {
alert("Invalid Content");
}
}
else {
alert("Blank value selected");
}
I have used Jquery function to check for regular expresion. This question is a linked question with
Using Jquery to add items in Listbox from Textbox
Now i can mark this as my final answer.

Sharepoint multi-column validation

I've got a custom list that contains multi collumns. The validation is made by a custom contenttype. Now I want a combination of two columns to be unique. Until know I did not found a way to solve this problem with on-board functions, so my idea was to use the eventreceiver or a customcontenttype.
What I tried:
ListEventReceiver
public override void ItemAdding(SPItemEventProperties properties)
{
if (properties.AfterProperties["a1"].ToString() == properties.AfterProperties["a2"].ToString())
{
properties.Status = SPEventReceiverStatus.CancelWithError;
properties.Cancel = true;
properties.ErrorMessage = "Failure";
}
base.ItemAdding(properties);
}
It works fine, but the error message is not show as a validation error. It is a new errorpage.
CustomContenttype
If I try to validate in a custom contenttype I can not access the value of an other field from the contenttype. So I can not compare two fields or check they are unique.
if you want to validation using ItemEventReceiver than you should use Sharepoint Error message page.
its will so you better of your Errormessage.I have used it.
Like :
if (properties.AfterProperties["a1"].ToString() == properties.AfterProperties["a2"].ToString())
{
properties.Status = SPEventReceiverStatus.CancelWithRedirectUrl;
properties.RedirectUrl = properties.WebUrl + "/_layouts/error.aspx?ErrorText=Entry is Failure";
}
or another way is Use PreSaveAction with javascript able to do valiation on list's forms.

Categories

Resources