MVC5 C# jQuery Unobtrusive Validation with ignore and Show/Hide Message - c#

My users have requested that I change one of the fields from being required to optional, but still show/hide the warning message. Trying to do this with as little refactoring as I can I added an allowsubmission property on my data annotation on the server and in the jquery method on the client (see below).
Is it possible to set an ignore class on an element while still hiding/showing the message? It seems the method fires the first time and then stops firing after the ignore class is added, so the message stays on the screen.
Or is there a better way? Thank you.
$(document).ready(function () {
$("form").validate().settings.ignore = ".ignore, :hidden";
});
$.validator.unobtrusive.adapters.add('dependentrange', ['minvalueproperty', 'maxvalueproperty', 'allowsubmission'],
function (options) {
options.rules.dependentrange = options.params;
if (options.message) {
$.validator.messages.dependentrange = options.message;
}
}
);
$.validator.addMethod('dependentrange', function (value, element, params) {
var minValue = parseFloat($('input[name="' + params.minvalueproperty + '"]').val());
var maxValue = parseFloat($('input[name="' + params.maxvalueproperty + '"]').val());
var currentValue = parseFloat(value);
// if there is a value check it. If for some reason the min and max can't be found return true because
// i do not know the values to validate. Usually that is a coding mistake
if (isNaN(currentValue) || minValue > currentValue || currentValue > maxValue) {
var message = $(element).attr('data-val-dependentrange');
$.validator.messages.dependentrange = $.validator.format(message, minValue, maxValue);
if (params.allowsubmission) {
// once this property is added, the method does not fire
$(element).addClass("ignore");
}
return false;
}
$(element).removeClass('ignore');
return true;
}, '');

I ended up using validators API to show and hide my own warning message while always return true.
$.validator.unobtrusive.adapters.add('dependentrange', ['minvalueproperty', 'maxvalueproperty'], function (options) {
options.rules['dependentrange'] = options.params;
if (options.message) {
options.messages['dependentrange'] = options.message;
}
});
$.validator.addMethod("dependentrange", function (value, element, params) {
var valKeyed = parseFloat(value),
$elem = $(element),
$warning = $elem.closest('div').nextAll('.alert-warning:first')
msg = $elem.data('val-dependentrange),
isValid = this.optional(element) || valKeyed >= parseFloat(params.minvalueproperty) && valKeyed <= parseFloat(params.maxvalueproperty);
// there are no from or two found, so just return true with no warning
if (!params.minvalueproperty || !params.maxvalueproperty) {
return true;
}
if (isValid) {
$warning.text('')
$warning.addClass('hidden');
}
else {
$warning.text(msg)
$warning.removeClass('hidden');
}
return true;
});

Related

WPF mvvm binding, get/set value: issue with preventing update value

I'm working in a WPF mvvm environment.
I have some binded vars and data from cs file to xaml.
One is different from others: it is the index of the selected tab in my tabsCollection. When the user has more than one tab opened and has got mods to save, I show him a dialog. If he cliks "ok", he proceed with the change of the tab, if he clicks "cancel", the tab must remain the same.
this is my code:
private int p_SelectedDocumentIndex;
public int SelectedDocumentIndex{ get { return p_SelectedDocumentIndex; }
set {
if (tabsCollection.Count() > 1 && CanSave() == true)
{
if (dm.ShowMessage1(ServiceContainer.GetService<DevExpress.Mvvm.IDialogService>("confirmYesNo")))
{
p_SelectedDocumentIndex = value;
base.RaisePropertiesChanged("SelectedDocumentIndex");
}
//else {
// CODE FOR NOT CHANGE THE VALUE
//}
}
else {
p_SelectedDocumentIndex = value;
base.RaisePropertiesChanged("SelectedDocumentIndex");
}
}
}
So, the question is: how can I not apply the change in the "set" section? (like an undo, I think)
This is simpliest way to do it, but, if this approach is incorrect, how can I do?
Previous failed attempts:
1)
p_SelectedDocumentIndex = p_SelectedDocumentIndex
base.RaisePropertiesChanged("SelectedDocumentIndex");
2)
base.RaisePropertiesChanged("SelectedDocumentIndex");
3)
nothing in the else branch
Dispatcher.CurrentDispatcher.BeginInvoke(new Action(() => SelectedDocumentIndex= p_SelectedDocumentIndex ), DispatcherPriority.Send);
This call arranges to revert the UI state to where it was before the operation started
I solved it. I've took the solution from here:
http://blog.alner.net/archive/2010/04/25/cancelling-selection-change-in-a-bound-wpf-combo-box.aspx
public int SelectedDocumentIndex{ get { return p_SelectedDocumentIndex; }
set {
// Store the current value so that we can
// change it back if needed.
var origValue = p_SelectedDocumentIndex;
// If the value hasn't changed, don't do anything.
if (value == p_SelectedDocumentIndex)
return;
// Note that we actually change the value for now.
// This is necessary because WPF seems to query the
// value after the change. The combo box
// likes to know that the value did change.
p_SelectedDocumentIndex = value;
if (tabsCollection.Count() > 1 && CanSave() == true)
{
if (!dm.ShowMessage1(ServiceContainer.GetService<DevExpress.Mvvm.IDialogService>("confirmYesNo")))
{
Debug.WriteLine("Selection Cancelled.");
// change the value back, but do so after the
// UI has finished it's current context operation.
Application.Current.Dispatcher.BeginInvoke(
new Action(() =>
{
Debug.WriteLine("Dispatcher BeginInvoke " + "Setting CurrentPersonCancellable.");
// Do this against the underlying value so
// that we don't invoke the cancellation question again.
p_SelectedDocumentIndex = origValue;
DocumentPanel p = tabsCollection.ElementAt(p_SelectedDocumentIndex);
p.IsActive = true;
base.RaisePropertiesChanged("SelectedDocumentIndex");
}),
System.Windows.Threading.DispatcherPriority.ContextIdle,
null
);
// Exit early.
return;
}
}
// Normal path. Selection applied.
// Raise PropertyChanged on the field.
Debug.WriteLine("Selection applied.");
base.RaisePropertiesChanged("SelectedDocumentIndex");
}
}
If your VM class is derived from DependencyObject then you can change your property to a DependecyProperty with a coerce callback which enables "undo" as follows:
public int SelectedDocumentIndex
{
get { return (int)GetValue(SelectedDocumentIndexProperty); }
set { SetValue(SelectedDocumentIndexProperty, value); }
}
public static readonly DependencyProperty SelectedDocumentIndexProperty =
DependencyProperty.Register("SelectedDocumentIndex", typeof(int), typeof(MyViewModel), new PropertyMetadata(0,
(d, e) =>
{
//Callback after value is changed
var vm = (MyViewModel)d;
var val = (int)e.NewValue;
}, (d, v) =>
{
//Coerce before value is changed
var vm = (MyViewModel)d;
var val = (int)v;
if (vm.tabsCollection.Count() > 1 && vm.CanSave() == true)
{
if (vm.dm.ShowMessage1(ServiceContainer.GetService<DevExpress.Mvvm.IDialogService>("confirmYesNo")))
{
//no coerce is needed
return v;
}
else
{
//should coerce to the previous value
return VM.SelectedDocumentIndex;
}
}
else
{
//no coerce is needed
return v;
}
}));

textbox accepts the following values in Javascript?

I have a textbox and i need to validate that it accepts only 1,1.5,2,2.5,3,3.5,...11.5
How to validate it.. pls tell the answer please.
$(document).on('keyup', '#Dia_Inch', function (e) {
Dia_Inch = $(this).val();
if (Dia_Inch.charAt(1) == ".") {
if (Dia_Inch.charAt(2) != "5") {
this.value = '';
$('#Dia_Inch').val("");
alert("Number must be between 0 and 11.5 If zero inches, must enter 0 Enter 1/2 inches as .5; -Ex. 3 and 1/2 inches entered as 3.5");
return false;
}
}
var val = isNumberInch(e);
if (val == false || Dia_Inch > 11.5) {
this.value = '';
$('#Dia_Inch').val("");
alert("Number must be between 0 and 11.5 If zero inches, must enter 0 Enter 1/2 inches as .5; -Ex. 3 and 1/2 inches entered as 3.5");
return false;
}
});
this my sample code.. but it wont be worked.
You can do this using jquery:
function validate(value){
var arr = [1,1.5,2,2.5,3,3.5,...11.5];
if($.inArray(value, arr) >= 0){
return true;
}
return false;
}
You'll have to modify this according to your needs.
Here is a fiddle: http://jsfiddle.net/5Cm2w/
Do not forget to update the array with your actual values.
This may solve your purpose.
$(function() {
$('button').on('click', function() {
var val = $.trim($('input[type="text"]').val());
if(val.length && $.isNumeric(val) && val.match(/^\d+(\.5{0,1})?$/)) {
alert('valid')
} else {
alert('invalid');
$.trim( $('input[type="text"]').val('') );
}
});
});
Demo
But if u want to allow up to 11.5 then
$(function() {
$('button').on('click', function() {
var val = $.trim($('input[type="text"]').val());
if(val.length && $.isNumeric(val) && val.match(/^[1-9]{1}[1]{0,1}(\.5{0,1})?$/)) {
alert('valid')
} else {
alert('invalid');
$.trim( $('input[type="text"]').val('') );
}
});
});
Demo

How to disable a radiobuttonlist using Java Script in Asp.net?

I have created a web form in which I have take certain fields like Name, Age and two radio button list (Required and ID). I want to enable disable certain fields on the value of one radiobutton list "Required". The "Required" Radiobuttonlist has two items, "YES", "NO". If I select yes, then certain fields should get enabled disabled and vice versa.
I am able to disable the texboxes, however I am not able to disable a radiobutton list "ID" which has to list items in it as taxId and PAN. I have used the following code for it
function EnableDisableID() {
if (document.getElementById("<%=rdID.ClientID %>") != null) {
var IDList = document.getElementById('<%= rdID.ClientID %>');
var isOpenID;
if (IDList != null) {
var openSubID = IDList.getElementsByTagName("input");
for (var i = 0; i < openSubID.length; i++) {
if (openSubID[i].checked) {
openSubID = openSubID[i].value;
}
}
}
if (openSubID == 'true') {
document.getElementById('<%=fbo1RadioButtonList.ClientID %>').disabled = false;
document.getElementById('<%=txtFbo1TaxId.ClientID %>').disabled = false;
}
if (isOpenSubAccount == 'false') {
alert("Printing..." + isOpenSubAccount);
document.getElementById('<%=fbo1RadioButtonList.ClientID %>').disabled = true;
document.getElementById('<%=txtFbo1TaxId.ClientID %>').disabled = true;
}
}
}
I am able to disable the FBO1TaxId, however, I am not able to disable the radiobutton list "fbo1RadioButtonList". How will I achieve it. do I have to treat its value individually?
I got the answer. I played with my code just a bit and came to a solution below:
function EnableDisableTaxID() {
if (document.getElementById("<%=rdOpeningSubAccount.ClientID %>") != null) {
var openSubAccountList = document.getElementById('<%= rdOpeningSubAccount.ClientID %>');
var rdFbo1TaxId = document.getElementById('<%=fbo1RadioButtonList.ClientID %>');
var rdFBO1Items = rdFbo1TaxId.getElementsByTagName('input');
var isOpenSubAccount;
if (openSubAccountList != null) {
var openSubAccount = openSubAccountList.getElementsByTagName("input");
for (var i = 0; i < openSubAccount.length; i++) {
if (openSubAccount[i].checked) {
isOpenSubAccount = openSubAccount[i].value;
}
}
}
if (isOpenSubAccount == 'true') {
for (var i = 0; i < rdFBO1Items.length; i++) {
rdFBO1Items[i].disabled = false;
}
document.getElementById('<%=txtFbo1TaxId.ClientID %>').disabled = false;
}
if (isOpenSubAccount == 'false') {
for (var i = 0; i < rdFBO1Items.length; i++) {
rdFBO1Items[i].disabled = true;
}
document.getElementById('<%=txtFbo1TaxId.ClientID %>').disabled = true;
}
}
}
You will have to loop over the radio buttons and disable each one. If your buttons are in a form, and you have a reference to the form, then you can use the common name for the buttons to get a collection. Loop over the collection and set each button's disabled property.
If you might either enable or disable the buttons, you can use a condition to set the value, something like:
var rbuttons = form.radioName;
var disabled = true; // disables buttons, set to false to enable
for (var i=0, iLen=rbuttons.length; i<iLen; i++) {
rbuttons[i].disabled = disabled;
}
To enable the buttons, set the disabled variable to false.

AutoComplete triggered with two Special characters and two datasources

I have played with:
https://github.com/experteer/autocompleteTrigger/
as following:
(function ($, window, document, undefined) {
$.widget("ui.autocompleteTrigger", {
//Options to be used as defaults
options: {
triggerStart: "%{",
triggerEnd: "}"
},
_create: function () {
this.triggered = false;
this.triggered2 = false;
this.element.autocomplete($.extend({
search: function () {
/**
* #description only make a request and suggest items if acTrigger.triggered is true
*/
var acTrigger = $(this).data("autocompleteTrigger");
if (acTrigger.triggered == true || acTrigger.triggered2 == true) {
return true;
} else {
return false;
}
},
select: function (event, ui) {
/**
* #description if a item is selected, insert the value between triggerStart and triggerEnd
*/
var acTrigger = $(this).data("autocompleteTrigger");
var text = this.value;
var trigger = acTrigger.options.triggerStart;
var trigger2 = acTrigger.options.triggerStart2;
var cursorPosition = acTrigger.getCursorPosition();
var lastTrigger1Position = text.substring(0, cursorPosition).lastIndexOf(trigger);
var lastTrigger2Position = text.substring(0, cursorPosition).lastIndexOf(trigger2);
var lastTriggerPosition;
if (lastTrigger1Position > lastTrigger2Position) {
lastTriggerPosition = lastTrigger1Position;
} else {
lastTriggerPosition = lastTrigger2Position;
}
var firstTextPart = text.substring(0, lastTriggerPosition + trigger.length) + ui.item.value +
acTrigger.options.triggerEnd;
this.value = firstTextPart + text.substring(cursorPosition, text.length);
acTrigger.triggered = false;
acTrigger.triggered2 = false;
// set cursor position after the autocompleted text
this.selectionStart = firstTextPart.length;
this.selectionEnd = firstTextPart.length;
return false;
},
focus: function () {
/**
* #description prevent to replace the hole text, if a item is hovered
*/
return false;
},
minLength: 0
}, this.options))
.bind("keyup", function (event) {
/**
* #description Bind to keyup-events to detect text changes.
* If the trigger is found before the cursor, autocomplete will be called
*/
var acTrigger = $(this).data("autocompleteTrigger");
if (event.keyCode != $.ui.keyCode.UP && event.keyCode != $.ui.keyCode.DOWN) {
var text = this.value;
var textLength = text.length;
var cursorPosition = acTrigger.getCursorPosition();
var lastString;
var query;
var lastTriggerPosition;
var lastTriggerPosition2;
var trigger = acTrigger.options.triggerStart;
var trigger2 = acTrigger.options.triggerStart2;
if (acTrigger.triggered && text != "") {
// call autocomplete with the string after the trigger
// Example: triggerStart = #, string is '#foo' -> query string is 'foo'
$(this).autocomplete("option", "source", '/UITests/LookupFirst');
lastTriggerPosition = text.substring(0, cursorPosition).lastIndexOf(trigger);
query = text.substring(lastTriggerPosition + trigger.length, cursorPosition);
$(this).autocomplete("search", query);
}
if (acTrigger.triggered2 && text != "") {
// call autocomplete with the string after the trigger
// Example: triggerStart = #, string is '#foo' -> query string is 'foo'
$(this).autocomplete("option", "source", '/UITests/LookupSec');
lastTriggerPosition2 = text.substring(0, cursorPosition).lastIndexOf(trigger2);
query = text.substring(lastTriggerPosition2 + trigger2.length, cursorPosition);
$(this).autocomplete("search", query);
}
else if (textLength >= trigger.length) {
// set trigged to true, if the string before the cursor is triggerStart
lastString = text.substring(cursorPosition - trigger.length, cursorPosition);
acTrigger.triggered = (lastString === trigger);
acTrigger.triggered2 = (lastString === trigger2);
}
}
});
},
/**
* #description Destroy an instantiated plugin and clean up modifications the widget has made to the DOM
*/
destroy: function () {
// this.element.removeStuff();
// For UI 1.8, destroy must be invoked from the
// base widget
$.Widget.prototype.destroy.call(this);
// For UI 1.9, define _destroy instead and don't
// worry about
// calling the base widget
},
/**
* #description calculates the the current cursor position in the bound textfield, area,...
* #returns {int} the position of the cursor.
*/
getCursorPosition: function () {
var elem = this.element[0];
var position = 0;
// dom 3
if (elem.selectionStart >= 0) {
position = elem.selectionStart;
// IE
} else if (elem.ownerDocument.selection) {
var r = elem.ownerDocument.selection.createRange();
if (!r) return data;
var tr = elem.createTextRange(), ctr = tr.duplicate();
tr.moveToBookmark(r.getBookmark());
ctr.setEndPoint('EndToStart', tr);
position = ctr.text.length;
}
return position;
}
});
})(jQuery, window, document);
and in the View:
$('input,textarea').autocompleteTrigger({
triggerStart: '#',
triggerEnd: '',
triggerStart2: '##',
sourceOption1: '/UITests/LookupFirst',
sourceOption2: '/UITests/LookupSec'
});
Controller Action Method(LookupSec is identical) is:
public ActionResult LookupFirst(string q)
{
var list = new List<string>()
{
"Asp",
"BASIC",
"COBOL",
"ColdFusion",
"Erlang",
"Fortran",
"Groovy",
"Java",
"JavaScript",
"Lisp",
"Perl",
"PHP",
"Python",
"Ruby",
"Scala",
"Scheme"
};
IEnumerable<string> data;
if (q != null)
{
data = list.Where(x => x.StartsWith(q));
}
else
data = list;
return Json(data, JsonRequestBehavior.AllowGet);
}
Now it supports two triggers # and # and two datasources for each one...
Problem is the searching doesnt work anymore, everything works as expected "Almost" but when i type something like "#as" it should filter the result but it doesnt!
any idea why this is not working ?
You seem to be using the LookupSec action to filter with the # character but in your question you have only shown the LookupFirst action which is associated with the # filter character. I have tested your code and it worked for # and not for # because LookupSec doesn't exist.
Once I have defined the LookupSec controller action it worked for both. Just be careful as right now you have hardcoded those action names in the widget itself so the sourceOption1 and sourceOption2 parameters will be completely ignored.
The query string parameter used by jquery autocomplete is called term, not q so fix your controller action as right now it isn't filtering anything:
public ActionResult LookupFirst(string term)
{
...
}

Asp.Net : Extended range validation

I'm using Asp.Net 2.0. I have a scenario where i need to check a user input against any of two ranges. For e.g. I need to check a textbox value against ranges 100-200 or 500-600. I know that i can hook up 2 Asp.Net RangeValidators to the TextBox, but that will try to validate the input against both the ranges, an AND condition,if you will. CustomValidator is an option, but how would I pass the 2 ranges values from the server-side. Is it possible to extend the RangeValidator to solve this particular problem?
[Update]
Sorry I didn't mention this, the problem for me is that range can vary. And also the different controls in the page will have different ranges based on some condition. I know i can hold these values in some js variable or hidden input element, but it won't look very elegant.
A CustomValidator should work. I'm not sure what you mean by "pass the 2 ranges values from the server-side". You could validate it on the server-side using a validation method like this:
void ValidateRange(object sender, ServerValidateEventArgs e)
{
int input;
bool parseOk = int.TryParse(e.Value, out input);
e.IsValid = parseOk &&
((input >= 100 || input <= 200) ||
(input >= 500 || input <= 600));
}
You will then need to set the OnServerValidate property of your CustomValidator to "ValidateRange", or whatever you happen to call it.
Is this the sort of thing you're after?
I do not believe this is possible using the standard RangeValidator control.
I did some searching and I believe your best solution is going to be to create your own CustomValidator control which you can include in your project to handle this scenario.
http://www.dotnetjunkies.ddj.com/Article/592CE980-FB7E-4DF7-9AC1-FDD572776680.dcik
You shouldn't have to compile it just to use it in your project, as long as you reference it properly.
You can use the RegularExpressionValidator with the ValidationExpression property set to
Edit: (whoops, 650 and 201 etc. were valid with the old pattern)
^(1\d{2}|200|5\d{2}|600)$
This will test the entered text for 100-200 and 500-600.
I extended the BaseValidator to achieve this. Its fairly simple once you understand how Validators work. I've included a crude version of code to demonstrate how it can be done. Mind you it's tailored to my problem(like int's should always be > 0) but you can easily extend it.
public class RangeValidatorEx : BaseValidator
{
protected override void AddAttributesToRender(System.Web.UI.HtmlTextWriter writer)
{
base.AddAttributesToRender(writer);
if (base.RenderUplevel)
{
string clientId = this.ClientID;
// The attribute evaluation funciton holds the name of client-side js function.
Page.ClientScript.RegisterExpandoAttribute(clientId, "evaluationfunction", "RangeValidatorEx");
Page.ClientScript.RegisterExpandoAttribute(clientId, "Range1High", this.Range1High.ToString());
Page.ClientScript.RegisterExpandoAttribute(clientId, "Range2High", this.Range2High.ToString());
Page.ClientScript.RegisterExpandoAttribute(clientId, "Range1Low", this.Range1Low.ToString());
Page.ClientScript.RegisterExpandoAttribute(clientId, "Range2Low", this.Range2Low.ToString());
}
}
// Will be invoked to validate the parameters
protected override bool ControlPropertiesValid()
{
if ((Range1High <= 0) || (this.Range1Low <= 0) || (this.Range2High <= 0) || (this.Range2Low <= 0))
throw new HttpException("The range values cannot be less than zero");
return base.ControlPropertiesValid();
}
// used to validation on server-side
protected override bool EvaluateIsValid()
{
int code;
if (!Int32.TryParse(base.GetControlValidationValue(ControlToValidate), out code))
return false;
if ((code < this.Range1High && code > this.Range1Low) || (code < this.Range2High && code > this.Range2Low))
return true;
else
return false;
}
// inject the client-side script to page
protected override void OnPreRender(EventArgs e)
{
base.OnPreRender(e);
if (base.RenderUplevel)
{
this.Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "RangeValidatorEx", RangeValidatorExJs(),true);
}
}
string RangeValidatorExJs()
{
string js;
// the validator will be rendered as a SPAN tag on the client-side and it will passed to the validation function.
js = "function RangeValidatorEx(val){ "
+ " var code=document.getElementById(val.controltovalidate).value; "
+ " if ((code < rangeValidatorCtrl.Range1High && code > rangeValidatorCtrl.Range1Low ) || (code < rangeValidatorCtrl.Range2High && code > rangeValidatorCtrl.Range2Low)) return true; else return false;}";
return js;
}
public int Range1Low
{
get {
object obj2 = this.ViewState["Range1Low"];
if (obj2 != null)
return System.Convert.ToInt32(obj2);
return 0;
}
set { this.ViewState["Range1Low"] = value; }
}
public int Range1High
{
get
{
object obj2 = this.ViewState["Range1High"];
if (obj2 != null)
return System.Convert.ToInt32(obj2);
return 0;
}
set { this.ViewState["Range1High"] = value; }
}
public int Range2Low
{
get
{
object obj2 = this.ViewState["Range2Low"];
if (obj2 != null)
return System.Convert.ToInt32(obj2);
return 0;
}
set { this.ViewState["Range2Low"] = value; }
}
public int Range2High
{
get
{
object obj2 = this.ViewState["Range2High"];
if (obj2 != null)
return System.Convert.ToInt32(obj2);
return 0;
}
set { this.ViewState["Range2High"] = value; }
}
}

Categories

Resources