How can I use Same Custom Validation Attribute Multiple Times on Same Field or simply enable AllowMultiple=true, for both server side and client side validation??
I have a following Custom Validation Attribute:
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property,
AllowMultiple = true, Inherited = true)]
public class RequiredIfAttribute : ValidationAttribute,IClientValidatable
{
public RequiredIfAttribute(string dependentProperties,
string dependentValues = "",
string requiredValue = "val")
{
}
}
Where in dependentProperties I can specify multiple dependant properties seperated by comma, in dependentValues I can specify for which values of dependant properties validation should process and finally in requiredValue I can specify expected value for the field to be validated.
In my model there are two properties LandMark, PinCode and I want to use validation as follows:
public string LandMark { get; set; }
[RequiredIf("LandMark","XYZ","500500")]
[RequiredIf("LandMark", "ABC", "500505")]
public string PinCode { get; set; }
The values here are just for example, as per it seems I can add the attribute multiple times and don't get any compile error, I have implemented TypeID in attribute and it works well from serverside if I remove client validation from it. But when I am implementing IClientValidatable on the attribute, it gives me an error:
"Validation type names in unobtrusive client validation rules must be unique."
Any help how can I solve it??
The Problem
Validation Attributes have two environments they can validate against:
Server
Client
Server Validation - Multiple Attributes Easy
If you have any attribute with:
[AttributeUsage(AttributeTargets.Property, AllowMultiple = true)]
public class RequiredIfAttribute : ValidationAttribute
And have put it on your class property like this:
public class Client
{
public short ResidesWithCd { get; set; };
[RequiredIf(nameof(ResidesWithCd), new[] { 99 }, "Resides with other is required.")]
public string ResidesWithOther { get; set; }
}
Then anytime the Server goes to validate an object (ex. ModelState.IsValid), it will check every ValidationAttribute on each property and call .IsValid() to determine validity. This will work fine, even if AttributeUsage.AllowMultiple is set to true.
Client Validation - HTML Attribute Bottleneck
If you enable client side by implementing IClientValidatable like this:
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
var modelClientValidationRule = new ModelClientValidationRule
{
ValidationType = "requiredif",
ErrorMessage = ErrorMessageString
};
modelClientValidationRule.ValidationParameters.Add("target", prop.PropName);
modelClientValidationRule.ValidationParameters.Add("values", prop.CompValues);
return new List<ModelClientValidationRule> { modelClientValidationRule };
}
Then ASP.NET will emit the following HTML when generated:
(As long as ClientValidationEnabled &
UnobtrusiveJavaScriptEnabled are enabled)
<input class="form-control" type="text" value=""
id="Client_CommunicationModificationDescription"
name="Client.CommunicationModificationDescription"
data-val="true"
data-val-requiredif="Communication Modification Description is required."
data-val-requiredif-target="CommunicationModificationCd"
data-val-requiredif-values="99" >
Data Attributes are the only vehicle we have for dumping rules into the client side validation engine which will search for any attributes on the page via a built in or custom adapter. And once part of the set of client side rules, it'll be able to determine the validity of each parsed rule with a built in or custom method.
So we can call jQuery Validate Unobtrusive to look for and parse these attributes by adding a custom adapter which will add a validation rule to the engine:
// hook up to client side validation
$.validator.unobtrusive.adapters.add('requiredif', ['target', 'values'], function (options) {
options.rules["requiredif"] = {
id: '#' + options.params.target,
values: JSON.parse(options.params.values)
};
options.messages['requiredif'] = options.message;
});
We can then tell that rule how function and determine validity by adding a custom method like this which will add a custom way to evaluate requiredif rules (as opposed to date rules or regex rules) which will rely on the parameters we loaded earlier through the adapter:
// test validity
$.validator.addMethod('requiredif', function (value, element, params) {
var targetHasCondValue = targetElHasValue(params.id, params.value);
var requiredAndNoValue = targetHasCondValue && !value; // true -> :(
var passesValidation = !requiredAndNoValue; // true -> :)
return passesValidation;
}, '');
Which all operates like this:
Solution
So, what have we learned? Well, if we want the same rule to appear multiple times on the same element, the adapter would have to see the exact set of rules multiple times per element, with no way to differentiate between each instance within multiple sets. Further, ASP.NET won't render the same attribute name multiple times since it's not valid html.
So, we either need to:
Collapse all the client side rules into a single mega attribute with all the info
Rename attributes with each instance number and then find a way to parse them in sets.
I'll explore Option One (emitting a single client side attribute), which you could do a couple ways:
Create a single Attribute that takes in multiple elements to validate on the server client
Keep multiple distinct server side attributes and then merge all attributes via reflection before emitting to the client
In either case you will have to re-write the client side logic (adapter/method) to take an array of values, instead of a single value at a time.
To we'll build/transmit a JSON serialized object that looks like this:
var props = [
{
PropName: "RoleCd",
CompValues: ["2","3","4","5"]
},
{
PropName: "IsPatient",
CompValues: ["true"]
}
]
Scripts/ValidateRequiredIfAny.js
Here's how we'll handle that in client side adapter / method:
// hook up to client side validation
$.validator.unobtrusive.adapters.add("requiredifany", ["props"], function (options) {
options.rules["requiredifany"] = { props: options.params.props };
options.messages["requiredifany"] = options.message;
});
// test validity
$.validator.addMethod("requiredifany", function (value, element, params) {
var reqIfProps = JSON.parse(params.props);
var anytargetHasValue = false;
$.each(reqIfProps, function (index, item) {
var targetSel = "#" + buildTargetId(element, item.PropName);
var $targetEl = $(targetSel);
var targetHasValue = elHasValue($targetEl, item.CompValues);
if (targetHasValue) {
anytargetHasValue = true;
return ;
}
});
var valueRequired = anytargetHasValue;
var requiredAndNoValue = valueRequired && !value; // true -> :(
var passesValidation = !requiredAndNoValue; // true -> :)
return passesValidation;
}, "");
// UTILITY METHODS
function buildTargetId(currentElement, targetPropName) {
// https://stackoverflow.com/a/39725539/1366033
// we are only provided the name of the target property
// we need to build it's ID in the DOM based on a couple assumptions
// derive the stacking context and depth based on the current element's ID/name
// append the target property's name to that context
// currentElement.name i.e. Details[0].DosesRequested
var curId = currentElement.id; // get full id i.e. Details_0__DosesRequested
var context = curId.replace(/[^_]+$/, ""); // remove last prop i.e. Details_0__
var targetId = context + targetPropName; // build target ID i.e. Details_0__OrderIncrement
// fail noisily
if ($("#" + targetId).length === 0)
console.error(
"Could not find id '" + targetId +
"' when looking for '" + targetPropName +
"' on originating element '" + curId + "'");
return targetId;
}
function elHasValue($el, values) {
var isCheckBox = $el.is(":checkbox,:radio");
var isChecked = $el.is(":checked");
var inputValue = $el.val();
var valueInArray = $.inArray(String(inputValue), values) > -1;
var hasValue = (!isCheckBox || isChecked) && valueInArray;
return hasValue;
};
Models/RequiredIfAttribute.cs
On the server side, we'll validate attributes like normal, but when we got to build the client side attributes, we'll look for all attributes and build one mega attribute
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Reflection;
using System.Web.Helpers;
using System.Web.Mvc;
[AttributeUsage(AttributeTargets.Property, AllowMultiple = true)]
public class RequiredIfAttribute : ValidationAttribute, IClientValidatable
{
public PropertyNameValues TargetProp { get; set; }
public RequiredIfAttribute(string compPropName, string[] compPropValues, string msg) : base(msg)
{
this.TargetProp = new PropertyNameValues()
{
PropName = compPropName,
CompValues = compPropValues
};
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
PropertyInfo compareProp = validationContext.ObjectType.GetProperty(TargetProp.PropName);
var compPropVal = compareProp.GetValue(validationContext.ObjectInstance, null);
string compPropValAsString = compPropVal?.ToString().ToLower() ?? "";
var matches = TargetProp.CompValues.Where(v => v == compPropValAsString);
bool needsValue = matches.Any();
if (needsValue)
{
if (value == null || value.ToString() == "" || value.ToString() == "0")
{
return new ValidationResult(FormatErrorMessage(null));
}
}
return ValidationResult.Success;
}
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
// at this point, who cares that we're on this particular instance - find all instances
PropertyInfo curProp = metadata.ContainerType.GetProperty(metadata.PropertyName);
RequiredIfAttribute[] allReqIfAttr = curProp.GetCustomAttributes<RequiredIfAttribute>().ToArray();
// emit validation attributes from all simultaneously, otherwise each will overwrite the last
PropertyNameValues[] allReqIfInfo = allReqIfAttr.Select(x => x.TargetProp).ToArray();
string allReqJson = Json.Encode(allReqIfInfo);
var modelClientValidationRule = new ModelClientValidationRule
{
ValidationType = "requiredifany",
ErrorMessage = ErrorMessageString
};
// add name for jQuery parameters for the adapter, must be LOWERCASE!
modelClientValidationRule.ValidationParameters.Add("props", allReqJson);
return new List<ModelClientValidationRule> { modelClientValidationRule };
}
}
public class PropertyNameValues
{
public string PropName { get; set; }
public string[] CompValues { get; set; }
}
Then we can bind that to our model by applying multiple attributes simultaneously:
[RequiredIf(nameof(RelationshipCd), new[] { 1,2,3,4,5 }, "Mailing Address is required.")]
[RequiredIf(nameof(IsPatient), new[] { "true" },"Mailing Address is required.")]
public string MailingAddressLine1 { get; set; }
Further Reading
ASP.NET MVC custom multiple fields validation by Stephen Muecke
Unobtrusive Client Validation in ASP.NET MVC 3 by Brad Wilson
Finally here I found the answer my-self.
Look at following article for solution
http://www.codeproject.com/KB/validation/MultipleDataAnnotations.aspx
The link in the accepted answer (http://www.codeproject.com/KB/validation/MultipleDataAnnotations.aspx) is buggy, and someone else has written an errata here which I would recommend reading first. The answer above does not handle inheritance.
I believe this alternate solution has some advantages (including support of inheritance), but remains far from perfect code - improvements appreciated.
this C# uses Json.NET and Stuart Leeks HTML Attribute provider
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web.Mvc;
using Newtonsoft.Json;
namespace DabTrial.Infrastructure.Validation
{
[AttributeUsage(AttributeTargets.Property, AllowMultiple = true, Inherited = true)]
public abstract class MultipleValidationAttribute : ValidationAttribute, IMetadataAware
{
private class Validation
{
public ICollection<string> ErrorMessage { get; set; }
public IDictionary<string, ICollection<object>> Attributes { get; set; }
}
private object _typeId = new object();
public const string attributeName = "multipleValidations";
public MultipleValidationAttribute()
{
}
public override object TypeId
{
get
{
return this._typeId;
}
}
public void OnMetadataCreated(ModelMetadata metadata)
{
Dictionary<string, Validation> allMultis;
if (metadata.AdditionalValues.ContainsKey(attributeName))
{
allMultis = (Dictionary<string, Validation>)metadata.AdditionalValues[attributeName];
}
else
{
allMultis = new Dictionary<string, Validation>();
metadata.AdditionalValues.Add(attributeName, allMultis);
}
foreach (var result in GetClientValidationRules(metadata))
{
if (allMultis.ContainsKey(result.ValidationType))
{
var thisMulti = allMultis[result.ValidationType];
thisMulti.ErrorMessage.Add(result.ErrorMessage);
foreach (var attr in result.ValidationParameters)
{
thisMulti.Attributes[attr.Key].Add(attr.Value);
}
}
else
{
var thisMulti = new Validation
{
ErrorMessage = new List<string>(),
Attributes = new Dictionary<string, ICollection<object>>()
};
allMultis.Add(result.ValidationType, thisMulti);
thisMulti.ErrorMessage.Add(result.ErrorMessage);
foreach (var attr in result.ValidationParameters)
{
var newList = new List<object>();
newList.Add(attr.Value);
thisMulti.Attributes.Add(attr.Key, newList);
}
}
}
}
public static IEnumerable<KeyValuePair<string, object>> GetAttributes(ModelMetadata metadata)
{
if (!metadata.AdditionalValues.ContainsKey(attributeName))
{
return null;
}
var returnVar = new List<KeyValuePair<string, object>>();
returnVar.Add(new KeyValuePair<string,object>("data-val", true));
var allMultis = (Dictionary<string, Validation>)metadata.AdditionalValues[attributeName];
foreach (var multi in allMultis)
{
string valName = "data-val-" + multi.Key;
returnVar.Add(new KeyValuePair<string,object>(valName, JsonConvert.SerializeObject(multi.Value.ErrorMessage)));
returnVar.AddRange(multi.Value.Attributes.Select(a=>new KeyValuePair<string,object>(valName + '-' + a.Key, JsonConvert.SerializeObject(a.Value))));
}
return returnVar;
}
public virtual IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata,
ControllerContext context)
{
throw new NotImplementedException("This function must be overriden");
}
public virtual IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata)
{
return GetClientValidationRules(metadata, null);
}
}
}
the Global.asax contains the code
HtmlAttributeProvider.Register((metadata) =>
{
return MultipleValidationAttribute.GetAttributes(metadata);
});
and the JavaScript (within a custom validators function)
function setMultiValidationValues(options, ruleName, values) {
var i = 0, thisRule;
for (; i < values.length; i++) {
thisRule = (i == 0) ? ruleName : ruleName + i;
options.messages[thisRule] = values[i].message;
delete values[i].message;
options.rules[thisRule] = values[i];
if (ruleName !== thisRule) {
(function addValidatorMethod() {
var counter = 0;
if (!$.validator.methods[ruleName]) {
if (++counter > 10) { throw new ReferenceError(ruleName + " is not defined"); }
setTimeout(addValidatorMethod, 100);
return;
}
if (!$.validator.methods[thisRule]) { $.validator.addMethod(thisRule, $.validator.methods[ruleName]); }
})();
}
}
}
function transformValidationValues(options) {
var rules = $.parseJSON(options.message),
propNames = [], p, utilObj,i = 0,j, returnVar=[];
for (p in options.params) {
if (options.params.hasOwnProperty(p)) {
utilObj = {};
utilObj.key = p;
utilObj.vals = $.parseJSON(options.params[p]);
propNames.push(utilObj);
}
}
for (; i < rules.length; i++) {
utilObj = {};
utilObj.message = rules[i];
for (j=0; j < propNames.length; j++) {
utilObj[propNames[j].key] = propNames[j].vals[i];
}
returnVar.push(utilObj);
}
return returnVar;
}
An example of its use is below:
C#
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Text.RegularExpressions;
using System.Web.Mvc;
namespace DabTrial.Infrastructure.Validation
{
[AttributeUsage(AttributeTargets.Property, AllowMultiple = true, Inherited = true)]
public class RegexCountAttribute : MultipleValidationAttribute
{
# region members
private string _defaultErrorMessageFormatString;
protected readonly string _regexStr;
protected readonly RegexOptions _regexOpt;
private int _minimumCount=0;
private int _maximumCount=int.MaxValue;
#endregion
#region properties
public int MinimumCount
{
get { return _minimumCount; }
set
{
if (value < 0) { throw new ArgumentOutOfRangeException(); }
_minimumCount = value;
}
}
public int MaximumCount
{
get { return _maximumCount; }
set
{
if (value < 0) { throw new ArgumentOutOfRangeException(); }
_maximumCount = value;
}
}
private string DefaultErrorMessageFormatString
{
get
{
if (_defaultErrorMessageFormatString == null)
{
_defaultErrorMessageFormatString = string.Format(
"{{0}} requires a {0}{1}{2} match(es) to regex {3}",
MinimumCount>0?"minimum of "+ MinimumCount:"",
MinimumCount > 0 && MaximumCount< int.MaxValue? " and " : "",
MaximumCount<int.MaxValue?"maximum of "+ MaximumCount:"",
_regexStr);
}
return _defaultErrorMessageFormatString;
}
set
{
_defaultErrorMessageFormatString = value;
}
}
#endregion
#region instantiation
public RegexCountAttribute(string regEx, string defaultErrorMessageFormatString = null, RegexOptions regexOpt = RegexOptions.None)
{
#if debug
if (minimumCount < 0) { throw new ArgumentException("the minimum value must be non-negative"); }
#endif
_regexStr = regEx;
DefaultErrorMessageFormatString = defaultErrorMessageFormatString;
_regexOpt = regexOpt;
}
#endregion
#region methods
protected override ValidationResult IsValid(object value,
ValidationContext validationContext)
{
var instr = (string)value;
int matchCount = 0;
if (MinimumCount > 0 && instr != null)
{
Match match = new Regex(_regexStr,_regexOpt).Match(instr);
while (match.Success && ++matchCount < MinimumCount)
{
match = match.NextMatch();
}
if (MaximumCount != int.MaxValue)
{
while (match.Success && ++matchCount <= MaximumCount)
{
match = match.NextMatch();
}
}
}
if (matchCount >= MinimumCount && matchCount <=MaximumCount)
{
return ValidationResult.Success;
}
string errorMessage = GetErrorMessage(validationContext.DisplayName);
return new ValidationResult(errorMessage);
}
protected string GetErrorMessage(string displayName)
{
return ErrorMessage ?? string.Format(DefaultErrorMessageFormatString,
displayName,
MinimumCount);
}
private bool HasFlag(RegexOptions options, RegexOptions flag)
{
return ((options & flag) == flag);
}
private string RegexpModifier
{
get
{
string options = string.Empty;
if (HasFlag(_regexOpt, RegexOptions.IgnoreCase)) { options += 'i'; }
if (HasFlag(_regexOpt, RegexOptions.Multiline)) { options += 'm'; }
return options;
}
}
public override IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata)
{
var returnVal = new ModelClientValidationRule {
ErrorMessage = GetErrorMessage(metadata.DisplayName),
ValidationType = "regexcount",
};
returnVal.ValidationParameters.Add("min",MinimumCount);
returnVal.ValidationParameters.Add("max",MaximumCount);
returnVal.ValidationParameters.Add("regex",_regexStr);
returnVal.ValidationParameters.Add("regexopt", RegexpModifier);
yield return returnVal;
}
#endregion
}
public class MinNonAlphanum : RegexCountAttribute
{
public MinNonAlphanum(int minimum) : base("[^0-9a-zA-Z]", GetDefaultErrorMessageFormatString(minimum))
{
this.MinimumCount = minimum;
}
private static string GetDefaultErrorMessageFormatString(int min)
{
if (min == 1)
{
return "{0} requires a minimum of {1} character NOT be a letter OR number";
}
return "{0} requires a minimum of {1} characters NOT be a letter OR number";
}
}
public class MinDigits : RegexCountAttribute
{
public MinDigits(int minimum) : base(#"\d", GetDefaultErrorMessageFormatString(minimum))
{
this.MinimumCount = minimum;
}
private static string GetDefaultErrorMessageFormatString(int min)
{
if (min == 1)
{
return "{0} requires a minimum of {1} character is a number";
}
return "{0} requires a minimum of {1} characters are numbers";
}
}
}
JavaScript:
$.validator.addMethod("regexcount", function (value, element, params) {
var matches = (value.match(params.regex)||[]).length
return matches >= params.min && matches <= params.max;
});
$.validator.unobtrusive.adapters.add("regexcount", ["min", "max", "regex", "regexopt"], function (options) {
var args = transformValidationValues(options), i=0;
for (; i < args.length; i++) {
args[i].regex = new RegExp(args[i].regex, args[i].regexopt);
delete args[i].regexopt;
}
setMultiValidationValues(options, "regexcount", args);
});
Related
using asp.net mvc 5
I have create a Custom conditional validation which is working perfectly when it is getting posted to controller but not working in client side -
and I am showing the code like below
if (!ModelState.IsValid)
{
return View("Index", model);
}
1 .I could not find any way in asp.net mvc which will work without the Jquery code - if you can suggest or show any other way without writing client side code manually that is preferable
If its not possible without writing client side code by myself , then how can i send two three error message from server , make it work in the client side
View Model
[ValidateTargetId]
public string TargetId{ get; set; }
[Required]
public string DependentProperty{ get; set; }
public SelectList DependentPropertyDropDownList { get; set; }
Custom Validator class
public class ValidateTargetIdAttribute : ValidationAttribute , IClientValidatable
{
protected override ValidationResult IsValid(object value,
ValidationContext validationContext)
{
object instance = validationContext.ObjectInstance;
Type type = instance.GetType();
PropertyInfo property = type.GetProperty("DependentProperty");
object propertyValue = property.GetValue(instance);
value = value == null ? "" : value.ToString();
if (propertyValue == null)
{
return null;
}
else
{
switch (propertyValue.ToString().ToUpper())
{
case "Case1":
if (!string.IsNullOrEmpty(value.ToString()))
{
return new
ValidationResult("target id should be blank");
}
break;
case "Case2":
if (value.ToString().Trim().Length != 15)
{
return new ValidationResult("Target Id should have length 15 ");
}
break;
case "Case3":
if (value.ToString().Trim().Length != 20)
{
return new ValidationResult("Target Id Should have length 20");
}
break;
}
return null;
}
}
//for client side
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
ModelClientValidationRule mvr = new ModelClientValidationRule();
mvr.ErrorMessage = "target id should be blank ";
mvr.ValidationType = "validtarget";
return new[] { mvr };
}
}
Jquery
$(function() {
jQuery.validator.addMethod('validtarget', function (value, element, params) {
// how to create this logic
}, '');
jQuery.validator.unobtrusive.adapters.add('validtarget', function (options) {
options.rules['validtarget] = {};
options.messages['validtarget'] = options.message;
});
}(jQuery));
I tried to compare two lists by using the Except method. But when I did, I got an error saying:
Cannot convert from 'Systems.Collections.Generic.List<>' to 'System.Linq.IQueryable<>'
'System.Collections.Generic.List<> does not contain a definition for 'Except' and the best extension method overload 'System.Linq.Queryable.Except(System.Linq.IQueryable, System.Collections.GEneric.IEnumerable)' has some invalid arguments
I also experienced this when I tried Intersect. I'm trying to compare Sent list and Result list (code and list shown below) and return items that does not have any match. So when I googled for how to do so, I came across the Except method as well as the Intersect.
public class Sent
{
public string Address;
public string Data;
}
public class Result
{
public string AddressOK;
public string DataOK;
}
var sent = new List<Sent>();
sent.Add(new Sent() { Address = linaddr1, Data = lindat1 });
var res = new List<Result>();
res.Add( new Result() { AddressOK = linaddr2, DataOK = lindat2 } );
//linaddr1 and 2, lindat1 and 2 contains the address and data shown in the list below
//taken from another part of the entire program
The lists look like such:
sent res
Address Data Address Data
04004C 55AA55 04004C 55AA55
040004 0720 040004 0720
040037 30
04004A FFFF 04004A FFFF
I only tried using this code:
var diff = sent.Except(res).ToList()
but as I've mentioned, it results with the aforementioned errors above.
EDIT: I edited the list. Sorry for that. It's just only a matter of the res list missing one or two or more items from the original list and then comparing both lists to see which item/s is/are missing from the res list.
Use Any:
using System;
using System.Collections.Generic;
using System.Linq;
public class Program
{
public static void Main()
{
var sent = new List<Sent>()
{
new Sent { Address = "04004C", Data = "55AA55" },
new Sent { Address = "040004", Data = "0720" },
new Sent { Address = "040037", Data = "31" },
new Sent { Address = "04004A", Data = "FFFF" }
};
var res = new List<Result> () {
new Result { AddressOK = "04004C", DataOK = "55AA55" },
new Result { AddressOK = "040004", DataOK = "0721" },
new Result { AddressOK = "040038 ", DataOK = "31" },
new Result { AddressOK = "04004A", DataOK = "FFFF" }
};
var diff =
sent.Where (s => !res.Any (r => s.Address == r.AddressOK && s.Data == r.DataOK ));
foreach (var item in diff)
{
Console.WriteLine("{0} {1}", item.Address, item.Data);
}
}
}
public class Sent
{
public string Address;
public string Data;
}
public class Result
{
public string AddressOK;
public string DataOK;
}
Output:
040004 0720
040037 31
Live Code: https://dotnetfiddle.net/ZVuiPd
The types Sent and Result are distinct types, but sent.Except(res) expects them to be the same. That's your first mistake.
The following is a simple (but incorrect) fix:
var diff =
sent
.Except(res.Select(x => new Sent() { Address = x.AddressOK, Data = x.DataOK }))
.ToList();
Even though this compiles, and runs, it doesn't remove the duplicates because your Sent doesn't override GetHashCode and Equals, hence it only compares references and not the actual properties.
You can either implement GetHashCode and Equals, or create an IEqualityComparer<Sent> to get this to work.
An IEqualityComparer<Sent> implementation might look like this:
public class SentEqualityComparer : IEqualityComparer<Sent>
{
public int GetHashCode(Sent sent)
{
return sent.Address.GetHashCode() ^ sent.Data.GetHashCode();
}
public bool Equals(Sent left, Sent right)
{
return (left.Address == right.Address) && (left.Data == right.Data);
}
}
And you would use it like so:
var diff =
sent
.Except(
res.Select(x => new Sent() { Address = x.AddressOK, Data = x.DataOK }),
new SentEqualityComparer())
.ToList();
This works as you expect.
The other option, to override GetHashCode and Equals, comes with an additional hurdle. The result of GetHashCode should not ever change throughout the lifetime of the object otherwise you can't use the object in a dictionary or any other data structure that relies on the hash code.
So, to make it work, you need to change Address & Data to be read-only.
Here is an implementation of your Sent class that will work correctly:
public sealed class Sent : IEquatable<Sent>
{
private readonly string _Address;
private readonly string _Data;
public string Address { get { return _Address; } }
public string Data { get { return _Data; } }
public Sent(string Address, string Data)
{
_Address = Address;
_Data = Data;
}
public override bool Equals(object obj)
{
if (obj is Sent)
return Equals((Sent)obj);
return false;
}
public bool Equals(Sent obj)
{
if (obj == null) return false;
if (!EqualityComparer<string>.Default.Equals(_Address, obj._Address)) return false;
if (!EqualityComparer<string>.Default.Equals(_Data, obj._Data)) return false;
return true;
}
public override int GetHashCode()
{
int hash = 0;
hash ^= EqualityComparer<string>.Default.GetHashCode(_Address);
hash ^= EqualityComparer<string>.Default.GetHashCode(_Data);
return hash;
}
}
If you are comfortable using an AOP component to automate the manual code of implementing IEquatable, another approach would be is to use Equals.Fody:
using System;
using System.Collections.Generic;
using System.Linq;
public class Program
{
public static void Main()
{
var a = new Sent { Address = "04004C", Data = "55AA55" };
var b = new Sent { Address = "04004C", Data = "55AA55" };
Console.WriteLine(a.Equals(b)); // True with use of an AOP, False with no AOP
var sent = new List<Sent>() {
new Sent { Address = "04004C", Data = "55AA55" },
new Sent { Address = "040004", Data = "0720" },
new Sent { Address = "040037", Data = "31" },
new Sent { Address = "04004A", Data = "FFFF" }
};
var res = new List<Result>() {
new Result { AddressOK = "04004C", DataOK = "55AA55" },
new Result { AddressOK = "040004", DataOK = "0721" },
new Result { AddressOK = "040038 ", DataOK = "31" },
new Result { AddressOK = "04004A", DataOK = "FFFF" }
};
var diff =
sent.Except(
res.Select(r => new Sent { Address = r.AddressOK, Data = r.DataOK })
);
foreach (var item in diff)
Console.WriteLine("{0} {1}", item.Address, item.Data);
}
}
[Equals]
public class Sent
{
public string Address;
public string Data;
[CustomEqualsInternal]
bool CustomLogic(Sent other)
{
return other.Address == this.Address && other.Data == this.Data;
}
}
public class Result
{
public string AddressOK;
public string DataOK;
}
Output:
True
040004 0720
040037 31
If you'll do map Result to Sent very often, you can further shorten your Linq query code to..
var diff = sent.Except(res.Select(r => (Sent)r));
..by automating the mapping of Result to Sent, use implicit operator:
[Equals]
public class Sent
{
public string Address;
public string Data;
[CustomEqualsInternal]
bool CustomLogic(Sent other)
{
return other.Address == this.Address && other.Data == this.Data;
}
public static implicit operator Sent(Result r)
{
return new Sent { Address = r.AddressOK, Data = r.DataOK };
}
}
#Kurisuchin
Suppose you have 2 list and in both you have ID property based on which you want to compare both list and want to store non matching item in third list.
In this Situation following Linq Query can help out.
var result = List2.Where(p => !List1.Any(p2 => p2.ID == p.ID)).ToList();
Asp .net MVC 3 application...
This is the View:
Grupa: <%= Html.DropDownListFor(x => x.Grupa, Model.ListaGrupe) %>
Produsul: <%= Html.DropDownListFor(x => x.Produs, Model.ListaProduse) %>
Cantitate: <%=Html.TextBoxFor(x => x.Cantitate, new { style = "width: 100px;" })%>
Pret: <%=Html.TextBoxFor(x => x.Pret, new { style = "width: 100px;", disabled = true})%>
TVA: <%= Html.TextBoxFor(x => x.TVA, new { style = "width: 100px;", disabled = true })%>
Valoare: <%= Html.TextBoxFor(x => x.NoTVA, new { style = "width: 120px;", disabled = true})%>
Valoare cu TVA: <%=Html.TextBoxFor(x => x.Total, new { style = "width: 120px;", disabled = true})%>
I am using some JQuery to change Pret, TVA, NoTVA and Total based on the values in Grupa, Produs and Cantitate so I don't want the user to modify the values inside them.
Probably disabled = true shoudn't be used. Then how can I make so the user can't modify the fields but the value to be posted to the controller's action?
You can also make them readonly rather than disabling them. On the other note, I think #Chris solution is better, that way your modified data will be posted back.
You can use Html.HiddenFor() and use a <span> or <div> instead. Their values will then be posted back.
Well, this is what i did up to now,
i didn't succeed to make a good, easy to use, readonly protection using encryption,
but i did manage to do something that i think might just do.
how it works:
When you use LockObject(o) an object, itterate the properties that have defined ProtectedAttribute defined for.
add the locked value to a list, specially made for this field.
! the list is kept in the user session (on the server side)
when the user submits the form, IsValid checks to see if the value is in the list of locked values. if yes, then it is all ok. otherwise, it must have been changed somehow.
! the number of values is not that big, and is temporary to the session, but if it is bothering someone, a simple lockList.remove(node); can easly be added when a value is validated.
Note: this can cause problem when the user uses Back buttons or Resubmit a form using Refresh.
tell me if you find any problems that this model does not take into account...
+ the Equalization is very naive, so it works only with value-types for time be.
Code:
Created an attribute named ProtectedAttribute:
[AttributeUsage(AttributeTargets.Property, AllowMultiple = true, Inherited = false)]
public class ProtectedPropertyAttribute : ValidationAttribute
{
private static Dictionary<string, LinkedList<object>> savedValues;
static ProtectedPropertyAttribute()
{
savedValues = (Dictionary<string, LinkedList<object>>)HttpContext.Current.Session["ProtectedAttributeData"];
if (savedValues != null)
return;
savedValues = new Dictionary<string, LinkedList<object>>();
HttpContext.Current.Session.Add("ProtectedAttributeData", savedValues);
}
public static void LockObject(object obj)
{
Type type = obj.GetType();
foreach (PropertyInfo property in type.GetProperties())
{
LockProperty(obj, property);
}
}
public static void LockProperty(object obj, PropertyInfo property)
{
ProtectedPropertyAttribute protectedAttribute =
(ProtectedPropertyAttribute)
property.GetCustomAttributes(typeof (ProtectedPropertyAttribute), false).FirstOrDefault();
if (protectedAttribute == null)
return;
if(protectedAttribute.Identifier == null)
protectedAttribute.Identifier = property.Name;
LinkedList<object> list;
if (!savedValues.TryGetValue(protectedAttribute.Identifier, out list))
{
list = new LinkedList<object>();
savedValues.Add(protectedAttribute.Identifier, list);
}
list.AddLast(property.GetValue(obj, null));
}
public string Identifier { get; set; }
public ProtectedPropertyAttribute()
{
}
public ProtectedPropertyAttribute(string errorMessage) : base(errorMessage)
{
}
public ProtectedPropertyAttribute(Func<string> errorMessageAccessor) : base(errorMessageAccessor)
{
}
protected override ValidationResult IsValid (object value, ValidationContext validationContext)
{
LinkedList<object> lockedValues;
if (Identifier == null)
Identifier = validationContext.DisplayName;
if (!savedValues.TryGetValue(Identifier, out lockedValues))
return new ValidationResult(FormatErrorMessage(validationContext.MemberName), new[] { validationContext.MemberName });
bool found = false;
LinkedListNode<object> node = lockedValues.First;
while (node != null)
{
if(node.Value.Equals(value))
{
found = true;
break;
}
node = node.Next;
}
if(!found)
return new ValidationResult(FormatErrorMessage(validationContext.MemberName), new[] { validationContext.MemberName });
return ValidationResult.Success;
}
}
place this attribute on any property of your model just as any other validation.
public class TestViewModel : Controller
{
[ProtectedProperty("You changed me. you bitch!")]
public string DontChangeMe { get; set; }
public string ChangeMe { get; set; }
}
in the controller, after you are finished with the viewmodel object,
you call ProtectedAttribute.LockObject(myViewModel)
public class TestController : Controller
{
public ActionResult Index()
{
TestViewModel vm = new TestViewModel {ChangeMe = "a1", DontChangeMe = "b1"};
ProtectedPropertyAttribute.LockObject(vm);
return View(vm);
}
public string Submit(TestViewModel vm)
{
string errMessage;
return !validate(out errMessage) ? "you are a baaad, man." + errMessage : "you are o.k";
}
private bool validate(out string errormessage)
{
if (ModelState.IsValid)
{
errormessage = null;
return true;
}
StringBuilder sb = new StringBuilder();
foreach (KeyValuePair<string, ModelState> pair in ModelState)
{
sb.Append(pair.Key);
sb.Append(" : <br/>");
foreach (ModelError err in pair.Value.Errors)
{
sb.Append(" - ");
sb.Append(err.ErrorMessage);
sb.Append("<br/>");
}
sb.Append("<br/>");
}
errormessage = sb.ToString();
return false;
}
}
i am using asp.net MVC 3 , in my module there are two types of payment modes 1. Wire transfer and 2. PayPal . Now depending on this type 1 and 2 the properties are to be kept Required or other data annotations ! how to do this ?
for eg :
There is a Radio button for payment type ,
If type 1- i.e Wire Transfer is selected then these fields should be validated - First name , last name , email,beneficiary name , bank name , bank no , ifsc code etc
if it is type 2- i.e PayPal then these fields are required - PayPal email .
This could be done by manual validation but is there some way to do it the right way with DataAnnotations?
Simon Ince's blog post seems to be outdated.
There is no need to use DataAnnotationsModelValidator or do a DataAnnotationsModelValidator registration.
You can use the following code:
[AttributeUsage(AttributeTargets.Property, AllowMultiple=false)]
public class RequiredIfAttribute : ValidationAttribute, IClientValidatable {
private const string _defaultErrorMessage = "'{0}' is required when {1} equals {2}.";
public string DependentProperty { get; set; }
public object TargetValue { get; set; }
public RequiredIfAttribute(string dependentProperty, object targetValue):base(_defaultErrorMessage) {
this.DependentProperty = dependentProperty;
this.TargetValue = targetValue;
}
public override string FormatErrorMessage(string name) {
return String.Format(CultureInfo.CurrentCulture, ErrorMessageString, name, DependentProperty, TargetValue);
}
protected override ValidationResult IsValid(object value, ValidationContext context) {
if (context.ObjectInstance != null) {
Type type = context.ObjectInstance.GetType();
PropertyInfo info = type.GetProperty(DependentProperty);
object dependentValue;
if (info != null) {
dependentValue = info.GetValue(context.ObjectInstance, null);
if (object.Equals(dependentValue, TargetValue)) {
if (string.IsNullOrWhiteSpace(Convert.ToString(value))) {
return new ValidationResult(ErrorMessage);
}
}
}
}
return ValidationResult.Success;
}
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context) {
ModelClientValidationRule rule = new ModelClientValidationRule();
rule.ErrorMessage = this.FormatErrorMessage(metadata.PropertyName);
rule.ValidationType = "requiredif";
rule.ValidationParameters.Add("depedentproperty", DependentProperty);
rule.ValidationParameters.Add("targetvalue", TargetValue);
yield return rule;
}
}
and the javascript side: if you are using jquery:
$.validator.unobtrusive.adapters.add('requiredif', ['depedentproperty', 'targetvalue'], function (options) {
options.rules["required"] = function (element) {
return $('#' + options.params.depedentproperty).val() == options.params.targetvalue
};
if (options.message) {
options.messages["required"] = options.message;
}
$('#' + options.params.depedentproperty).blur(function () {
$('#' + options.element.name).valid();
});
});
I've updated my example to use MVC 3, so that one is more up to date.
http://blogs.msdn.com/b/simonince/archive/2011/02/04/conditional-validation-in-asp-net-mvc-3.aspx
You could write a custom validator attribute and decorate your model with it:
[AttributeUsage(AttributeTargets.Class, AllowMultiple = false)]
public class CustomValidationAttribute : ValidationAttribute
{
public override bool IsValid(object value)
{
var model = value as MyViewModel;
if (model == null)
{
return false;
}
if (model.WireTransfer == 1)
{
return !string.IsNullOrEmpty(model.FirstName) &&
!string.IsNullOrEmpty(model.LastName);
}
else if (model.WireTransfer == 2)
{
return !string.IsNullOrEmpty(model.PaypalEmail);
}
return false;
}
}
and then in your main Model:
[CustomValidation]
public class MyViewModel
{
public string FirstName { get; set; }
public string LastName { get; set; }
...
}
I have used the approach from Simon Ince's blog post and it works well. Basically he creates a RequiredIf data attribute where you can specify the other property and value that must be true in order to make the current field required.
I have two fields in my form
AccountNumber
ReverseAccountNumber
Can i use data annotations to validate that the value of "ReverseAccountNumber" textbox is equal to the reversed value of "AccountNumber".
i.e.
AccountNumber = 12345
ReverseAccountNumber = 54321
i expect the validation to occur on the lostFocus event of the ReverseAccountNumber textbox.
I think i can do this using IDataErrorInfo, However I believe this would require a POST first before validation occurs, and i consider it a last resort.
Simply add a validation attribute to the class (not the properties) and evaluate the class object to compare the two properties. As for the client side, ASP.NET MVC 3 should be able to generate proper client-side validation for this (although I have not tried it myself since Iam still using xVal).
CustomAttribute
[AttributeUsage(AttributeTargets.Property, AllowMultiple = true, Inherited = true)]
public sealed class ReversStringMatchAttribute : ValidationAttribute
{
public string Property { get; set; }
public ReversStringMatchAttribute()
{ }
public override bool IsValid(object value)
{
return true;
}
}
CustomValidator
public class ReversStringValidator : DataAnnotationsModelValidator<ReversStringMatchAttribute>
{
string property;
public ReversStringValidator(ModelMetadata metadata, ControllerContext context, ReversStringMatchAttribute attribute)
: base(metadata, context, attribute)
{
property = attribute.Property;
}
public override IEnumerable<ModelClientValidationRule> GetClientValidationRules()
{
var rule = new ModelClientValidationRule
{
ErrorMessage = Attribute.ErrorMessage,
ValidationType = "reversStringValidator"
};
rule.ValidationParameters.Add("propertyname", property);
return new[] { rule };
}
}
Java Script
Sys.Mvc.ValidatorRegistry.validators["reversStringValidator"] = function (rule) {
//initialization
//return validator function
return function (value, context) {
var field = $get(rule.ValidationParameters['propertyname']);
if (field == null)
return "Property name is invalid!";
var s1 = field.value;
if (s1) {
if (value) {
var reverse = value.split("").reverse().join("");
if (s1 != reverse.toString()) {
return rule.ErrorMessage;
}
} else {
return rule.ErrorMessage;
}
}
return true;
}
};
then use it on your property
public class AccountViewModel
{
[Required(ErrorMessage="Account Number is Required")]
public string AccountNumber { get; set; }
[ReversStringMatch(ErrorMessage = "The value doesn't match the Account Number", Property="AccountNumber")]
public string ReverseAccountNumber { get; set; }
}
i have some doubts on the $get validation method in javascript but it works, for now.