我正在使用带有DataAnnotations的ASP.NET MVC.我创建了以下自定义ValidationAttribute,它可以正常工作.
public class StringRangeAttribute : ValidationAttribute
{
public int MinLength { get; set; }
public int MaxLength { get; set; }
public StringRangeAttribute(int minLength, int maxLength)
{
this.MinLength = (minLength < 0) ? 0 : minLength;
this.MaxLength = (maxLength < 0) ? 0 : maxLength;
}
public override bool IsValid(object value)
{
//null or empty is <em>not</em> invalid
string str = (string)value;
if (string.IsNullOrEmpty(str))
return true;
return (str.Length >= this.MinLength && str.Length <= this.MaxLength);
}
}
Run Code Online (Sandbox Code Playgroud)
但是,出现的错误消息是标准的"字段*无效".我想将其更改为:"[DisplayName]必须介于[minlength]和[maxlength]之间",但我无法弄清楚如何从此类中获取DisplayName甚至字段的名称.
谁知道?
我想知道实体框架在数据验证方面的一般建议是什么.我对EF相对较新,但似乎有两种主要的数据验证方法.
第一种是为模型创建部分类,然后执行数据验证并更新规则违规的集合.这可以在http://msdn.microsoft.com/en-us/library/cc716747.aspx上找到
另一种是使用数据注释,然后让注释执行数据验证.Scott Guthrie在他的博客http://weblogs.asp.net/scottgu/archive/2010/01/15/asp-net-mvc-2-model-validation.aspx上解释了这一点.
我想知道一个人的好处是什么.似乎数据注释将是首选机制,特别是当您转移到RIA服务时,但我想确保我没有遗漏某些东西.当然,没有什么可以排除在一起使用它们.
谢谢
约翰
要在我的编辑视图中呈现HTML,我使用帮助器@Html.EditorForModel().
我的模特:
[Required(ErrorMessage = "Campo obrigatório")]
[Display(Name = "Nome completo")]
public string Name { get; set; }
[Required(ErrorMessage = "Campo é obrigatório")]
[StringLength(100, ErrorMessage = "A {0} deve ter pelo menos {2} characteres.", MinimumLength = 6)]
[DataType(DataType.Password)]
[Display(Name = "Senha")]
public string Password { get; set; }
[DataType(DataType.Password)]
[Display(Name = "Confirmar senha")]
[Compare("Password", ErrorMessage = "A nova senha e a confirmação da senha não conincidem.")]
public string ConfirmPassword { get; set; }
[Required(ErrorMessage = "Campo obrigatório")]
[Display(Name = …Run Code Online (Sandbox Code Playgroud) scaffolding mvc-editor-templates data-annotations razor asp.net-mvc-3
在我的项目中,我有这个窗口来添加新Contact对象
我的问题是如何确认我将属性应用于WPF的窗前,仿佛我做Asp.net MVC ..喜欢[Required]和一些[ReularExpression()]
<Window x:Class="WPFClient.AddNewContact"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="AddNewContact" Height="401" Width="496" mc:Ignorable="d" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:my="clr-namespace:WPFClient.PhoneBookServiceReference" Loaded="Window_Loaded">
<Window.Resources>
</Window.Resources>
<Grid Height="355" Width="474">
<GroupBox Header="Add Contact" Margin="0,0,0,49">
<Grid HorizontalAlignment="Left" Margin="21,21,0,0" Name="grid1" VerticalAlignment="Top" Height="198" Width="365">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="194" />
<ColumnDefinition Width="64*" />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="53" />
<RowDefinition Height="17*" />
</Grid.RowDefinitions>
<Label Content="Name:" Grid.Column="0" Grid.Row="0" HorizontalAlignment="Left" Margin="3" VerticalAlignment="Center" />
<TextBox Grid.Column="1" Grid.Row="0" Height="23" …Run Code Online (Sandbox Code Playgroud) FluentValidation 库相对于 .NET System.ComponentModel.DataAnnotations 有什么优势?
它是否提供更灵活的验证,因为它没有在属性上进行注释(静态字段验证),例如根据另一个属性值验证属性?
我想弄清楚是否有适当的方法可以使用 DataAnnotations 实现这一点:
有一个数组或字符串列表,其中数组或列表中的最大元素数为 2 个项目,并且每个字符串可能只有 255 个字符长。这是否有效:
[MaxLength(2)]
[StringLength(255)]
public string[] StreetAddress { get; set; }
Run Code Online (Sandbox Code Playgroud)
我宁愿不必创建一个新类来保存一个字符串Value属性来将每个字符串限制为 255 个字符。
我正在开发用于在 Visual Studio 2015 中进行验证的 ASP.NET MVC 5.2.3 自定义数据注释。它需要采用任意数量的字段并确保如果有一个值,它们都必须有一个值;如果它们都是空/空白,应该没问题。
一些例子有帮助:
但是,我不确定如何进行客户端验证,其中要验证的字段数量未知。
您如何使用接口GetClientValidationRules()方法的实现将其传递给客户端IClientValidatable?
另外,如何将这个新的数据注释应用到我的视图模型上的属性?会是这个样子吗?
[MultipleRequired("AppNumber", "UserId", /* more fields */), ErrorMessage = "Something..."]
[DisplayName("App #")]
public int AppNumber { get; set; }
[DisplayName("User ID")]
public int UserId { get; set; }
Run Code Online (Sandbox Code Playgroud)
这是我使用MultipleRequiredAttribute自定义数据注释类所能得到的:
public class MultipleRequiredAttribute : ValidationAttribute, IClientValidatable
{
private readonly string[] _fields;
public MultipleRequiredAttribute(params string[] fields)
{
_fields = fields;
}
protected override ValidationResult IsValid(object value, …Run Code Online (Sandbox Code Playgroud) 假设我有一个控制器,CatController其中包含GET,POST和PUT操作.它们都使用相同的Cat资源,如下所示:
public class CatDto {
public int Id { get; set; }
[Required]
public string Name { get; set; }
[Required]
public bool IsFriendly {get; set; }
}
Run Code Online (Sandbox Code Playgroud)
但是,仅在创建新cat(POST)时才需要Name和IsFriendly属性,但在更新它(PUT)时可选,以允许仅更新单个属性.
到目前为止我处理这个问题的方法只是有两个类,a CreateCat和UpdateCat具有相同属性但不同的数据注释.但是我不想要维护两个几乎相同的类.
我当然可以在每个操作中手动验证模型,但数据注释对于诸如全局模型验证器和自动生成Swagger架构之类的东西非常有用.
我也使用Swagger模式自动生成SDK(使用ApiMatic),这导致生成(CreateCat和UpdateCat)两个重复的类,实际上应该只是一个资源(Cat).
有没有另一种方法来实现我只想用一个班级做的事情?
我的代码:
启动.cs
public void ConfigureServices(IServiceCollection services)
{
...
services.AddLocalization(options => options.ResourcesPath = "Resources");
services.AddMvc()
.AddViewLocalization(LanguageViewLocationExpanderFormat.Suffix)
.AddDataAnnotationsLocalization(options =>
{
options.DataAnnotationLocalizerProvider = (type, factory) =>
factory.Create(typeof(SharedResource));
});
...
}
Run Code Online (Sandbox Code Playgroud)
共享资源.cs
namespace MyProj.Classes
{
/// <summary>
/// Dummy class to group shared resources
/// </summary>
public class SharedResource
{
}
}
Run Code Online (Sandbox Code Playgroud)
FooViewModel.cs
public class FooViewModel
{
[Required(ErrorMessage = "EmailRequired")]
[EmailAddress(ErrorMessage = "EmailIsNotValid")]
[Display(Name = "Email")]
[DataType(DataType.EmailAddress)]
public string Email { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
FooPage.cshtml
...
<input asp-for="Email" class="form-control">
<div …Run Code Online (Sandbox Code Playgroud) 我正在创建 asp.net mvc 应用程序,其中将错误消息存储在数据库中,现在我想在用户单击提交时使用必需的字段注释而不是自定义 js 验证,我的模型如下所示,
[Required(ErrorMessage = "static error message")]
public string AttributeValue { get; set; }
Run Code Online (Sandbox Code Playgroud)
我想添加动态错误消息而不是 -> (静态错误消息)
有没有办法从控制器添加动态错误消息。
data-annotations ×10
c# ×5
asp.net-mvc ×4
validation ×3
asp.net ×1
asp.net-core ×1
localization ×1
razor ×1
scaffolding ×1
viewmodel ×1
wpf ×1