我正在尝试创建一个UniqueAttribute使用System.ComponentModel.DataAnnotations.ValidationAttribute
我希望这是通用的,因为我可以传递Linq DataContext,表名,字段并验证传入值是否唯一.
这是一个不可编译的代码片段,我现在卡在这里:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel.DataAnnotations;
using System.Data.Linq;
using System.ComponentModel;
namespace LinkDev.Innovation.Miscellaneous.Validation.Attributes
{
public class UniqueAttribute : ValidationAttribute
{
public string Field { get; set; }
public override bool IsValid(object value)
{
string str = (string)value;
if (String.IsNullOrEmpty(str))
return true;
// this is where I'm stuck
return (!Table.Where(entity => entity.Field.Equals(str)).Any());
}
}
}
Run Code Online (Sandbox Code Playgroud)
我应该在我的模型中使用它如下:
[Required]
[StringLength(10)]
[Unique(new DataContext(),"Groups","name")]
public string name { get; set; }
Run Code Online (Sandbox Code Playgroud)
编辑:请注意,根据这个:为什么C#禁止通用属性类型? 我不能使用属性的泛型类型.
所以我的新方法是使用Reflection/Expression树来动态构建Lambda表达式树.
我正在尝试创建一个最小长度验证属性,该属性将强制用户在文本框中输入指定的最小字符数
public sealed class MinimumLengthAttribute : ValidationAttribute
{
public int MinLength { get; set; }
public MinimumLengthAttribute(int minLength)
{
MinLength = minLength;
}
public override bool IsValid(object value)
{
if (value == null)
{
return true;
}
string valueAsString = value as string;
return (valueAsString != null && valueAsString.Length >= MinLength);
}
}
Run Code Online (Sandbox Code Playgroud)
在MinimumLengthAttribute的构造函数中,我想设置错误消息,如下所示:
ErrorMessage ="{0}必须至少为{1}个字符"
如何获取属性的显示名称以便填充{0}占位符?
当我执行以下操作时:
`[Range(1910, DateTime.Now.Year)]
public int Year { get; set; }`
Run Code Online (Sandbox Code Playgroud)
我收到以下错误:
An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type
有什么想法吗?
我的模型上有以下属性
[Display(Name = "MyProperty")]
[StringLength(10)]
public string MyProperty
{
get;set;
}
Run Code Online (Sandbox Code Playgroud)
以及以下EditorFor模板
<%@ Page Language="C#" MasterPageFile="Template.Master" Inherits="System.Web.Mvc.ViewPage" %>
<asp:Content ID="Content1" ContentPlaceHolderID="Data" runat="server">
<%= Html.TextBox("", Model)%>
</asp:Content>
Run Code Online (Sandbox Code Playgroud)
我遇到的问题是StringLength属性(可以理解),没有设置为限制文本框大小.我的答案是我应该如何获取在模板中设置的属性?
谢谢
考虑一下我有这两个属性:
public class Test
{
[Required(ErrorMessage = "Please Enetr Age")]
public System.Int32 Age { get; set; }
[Required(ErrorMessage = "Choose an option")]
public System.Boolean IsOld { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
当用户输入例如15 for for Age并选择" Yes"for时IsOld,我返回一个正确的异常Age或IsOld.我已经习惯CustomValidation了,但因为我的验证必须是静态的,所以我无法访问其他属性.我怎么能这样做DataAnnotation呢?
我在我的视图中有这一行:
@Html.EditorForModel()
Run Code Online (Sandbox Code Playgroud)
这是我的ViewModel:
public class CommentForm
{
public int Id { get; set; }
[DisplayName("Kommentar"), DataType(DataType.MultilineText)]
public string Comment { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
问题是Id在表单中呈现为文本字段.实际上,我只想Id在表单中使用动作.是否有一个属性告诉编辑器不要呈现属性Id?
我在MSDN上阅读这篇文章并没有真正描述太多.它表示它用于指定与数据列或参数关联的数据类型.说得通.这是否意味着我应该在我的所有属性上使用它?我假设没有.那么为什么有一个DataType.Text,当你将一个属性作为字符串时似乎没用.
我发现它使用多行文本作为数据类型来在客户端创建textarea而不是仅仅一行文本输入元素.但这与数据列或参数有何关系?
我还假设它也会验证它,因为我使用了DataType.Url,但无论是否输入了Url,它都会通过.与DataType.Email相同.有什么我做错了或者我需要使用RegEx吗?
是否可以向现有的DataAnnotations中添加新的数据类型(我不是在寻找验证器而是原始数据类型)。例如
弯腰你有
[DataType(DataType.Html)]
public string Footer {get; set;}
Run Code Online (Sandbox Code Playgroud)
并添加到混合中 ~Views/Shared/EditorTemplates/Html.cshtml
我希望能够添加[DataType(DataType.CSS)],从理论上讲,我可以使用a UIHint来添加特定视图,但是如果可能的话,我想在更早的阶段进行操作并指定数据类型,而不是依赖于UI提示。
任何指针将不胜感激。快速搜索SO似乎对自定义元数据类型,自定义验证器和多个数据类型有很多答案,但是我似乎找不到用于添加新核心数据类型的方法。
我有一个应用代码第一个数据注释的类,但在MVC视图上,我发现出现默认错误消息而不是自定义错误消息.请问任何ssugesstion
public class PaymentModel
{
[DisplayName("Email Address")]
[Required]
[RegularExpression(@"^[-a-z0-9~!$%^&*_=+}{\'?]+(\.[-a-z0-9~!$%^&*_=+}{\'?]+)*@([a-z0-9_][-a-z0-9_]*(\.[-a-z0-9_]+)*\.(aero|arpa|biz|com|coop|edu|gov|info|int|mil|museum|name|net|org|pro|travel|mobi|[a-z][a-z])|([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}))(:[0-9]{1,5})?$", ErrorMessage = "Please enter a valid Email Address")]
public string EmailAddress { get; set; }
[DisplayName("Credit Card Number")]
[Required]
[StringLength(16, ErrorMessage = "The {0} must be at least {1} characters long.", MinimumLength = 3)]
public int CreditCardNumber { get; set; }
[Required]
[StringLength(3, ErrorMessage = "The {0} must be at least {1} characters long.", MinimumLength = 3)]
public int Cvv { get; set; }
[DisplayName("Expiry Month")]
[Required]
public int ExpiryMonth { …Run Code Online (Sandbox Code Playgroud) 以下简单的实体...
public class MyEntity
{
[MaxLength(100)]
[Required]
public string Name { get; private set; }
}
Run Code Online (Sandbox Code Playgroud)
...是否可以读取正在装饰"Name"属性的数据注释并验证ChangeName方法中指定的值,以便ValidationResults可以连接到其他验证结果.我假设使用MethodInfo或PropertyInfo对象有些怎么样?
我有这个,但感觉非常笨拙.
public ValidationResult ChangeName(string value)
{
var property = GetType().GetProperty("Name");
var attribute = property.GetCustomAttributes(typeof(MaxLengthAttribute), true)[0] as MaxLengthAttribute;
if (attribute == null) return null; //yield break;
if (value.Length > attribute.Length)
{
return new ValidationResult(NameValidation.NameTooLong);
}
return null;
}
Run Code Online (Sandbox Code Playgroud)
我希望能够从我的验证器中的方法调用ChangeName(value),就像这样.
private IEnumerable<ValidationResult> ValidateMyEntity(MyEntityAddCommand command)
{
MyEntity myEntity = new MyEntity();
yield return myEntity.ChangeName(command.Name);
}
Run Code Online (Sandbox Code Playgroud)
到目前为止我读到的大多数内容都说数据注释是针对CRUD而不是DDD,但为什么不使用它们,因为它们是描述验证行为的好方法,它将与我的MVC视图模型上的数据注释验证一致.有没有更好或更简洁的方法可以做到这一点?所有建议都赞赏.
c# validation domain-driven-design command-pattern data-annotations