我想创建一个自定义验证属性,我想在其中将my属性的值与我的模型类中的另一个属性值进行比较.例如我在我的模型类中:
...
public string SourceCity { get; set; }
public string DestinationCity { get; set; }
Run Code Online (Sandbox Code Playgroud)
我想创建一个自定义属性来像这样使用它:
[Custom("SourceCity", ErrorMessage = "the source and destination should not be equal")]
public string DestinationCity { get; set; }
//this wil lcompare SourceCity with DestinationCity
Run Code Online (Sandbox Code Playgroud)
我要怎么去那儿?
我正在寻找关于实现执行以下操作的验证属性的最佳方法的一些建议.
模型
public class MyInputModel
{
[Required]
public int Id {get;set;}
public string MyProperty1 {get;set;}
public string MyProperty2 {get;set;}
public bool MyProperty3 {get;set;}
}
Run Code Online (Sandbox Code Playgroud)
我想至少使用一个值得到prop1 prop2 prop3,如果prop3是填充它的唯一值,它不应该等于false.我将如何为此编写验证属性(s?)?
谢谢你的帮助!
我正在尝试使用正则表达式来验证电话号码,并在提交无效的号码或电话号码时返回错误.
MVC代码:
<ol class="row">
<li class="cell" style="width: 20%;">Phone Number:</li>
<li class="cell last" style="width: 60%;">
@Html.TextBoxFor(model => model.PhoneNumber, new { @class = "textbox" })
@Html.ValidationMessageFor(model => model.PhoneNumber)
</li>
</ol>
Run Code Online (Sandbox Code Playgroud)
C#代码:
[DataType(DataType.PhoneNumber)]
[Display(Name = "Phone Number")]
[Required(ErrorMessage = "Phone Number Required!")]
[RegularExpression(@"^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$",
ErrorMessage = "Entered phone format is not valid.")]
public string PhoneNumber { get; set; }
Run Code Online (Sandbox Code Playgroud)
但是,输入框不会向用户显示消息,表明提交的电话号码无效.
我知道在MVC中有很多方法可以进行模型验证,并且有很多关于这个主题的文档.不过,我不太清楚什么是用于验证的性能,最好的方法模型这是"子模型"的同一类型.
请记住以下内容
TryUpdateModel/TryValidateModel方法MainModel该类有一个强类型视图,用于呈现整个显示视图这可能听起来有点令人困惑但我会抛出一些代码来澄清.以下面的类为例:
MainModel:
class MainModel{
public SomeSubModel Prop1 { get; set; }
public SomeSubModel Prop2 { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
SomeSubModel:
class SomeSubModel{
public string Name { get; set; }
public string Foo { get; set; }
public int Number { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
MainModelController:
class MainModelController{
public ActionResult MainDisplay(){
var main = db.retrieveMainModel();
return View(main);
}
[HttpGet]
public ActionResult EditProp1(){
//hypothetical retrieve …Run Code Online (Sandbox Code Playgroud) c# model-view-controller asp.net-mvc model-validation validationattribute
我一直在剃刀视图中将枚举表示为隐藏字段,并将其发布回动作结果.
我注意到,当它绑定HTML中提供的字符串值时,它会自动验证枚举的值.
/// <summary>
/// Quiz Types Enum
/// </summary>
public enum QuizType
{
/// <summary>
/// Scored Quiz
/// </summary>
Scored = 0,
/// <summary>
/// Personality Type Quiz
/// </summary>
Personality = 1
}
Run Code Online (Sandbox Code Playgroud)
剃刀:
@Html.HiddenFor(x => x.QuizType)
Run Code Online (Sandbox Code Playgroud)
呈现的HTML:
<input data-val="true" data-val-required="Quiz Type is not valid" id="QuizType" name="QuizType" type="hidden" value="Scored">
Run Code Online (Sandbox Code Playgroud)
如果我将DOM中的值更改为不正确的值并提交表单,则ModelState.IsValid返回false并将以下错误添加到ModelState:
"The value 'myincorrectvalue' is not valid for QuizType."
Run Code Online (Sandbox Code Playgroud)
这一切都很好,但我认为如果我创建了一个视图模型,我必须在我的视图模型上显式设置验证规则,例如[Required]属性.
此外,还有一个专门针对此调用的验证属性EnumDataType.
[EnumDataType(typeof(QuizType))]
public QuizType QuizType { get; set; }
Run Code Online (Sandbox Code Playgroud)
题 …
我有一种复杂的模型.
我有我的UserViewModel,有几个属性,其中两个是HomePhone和WorkPhone.两种类型PhoneViewModel.在PhoneViewModel我有CountryCode,AreaCode和Number所有字符串.我想使CountryCode可选的,但AreaCode与Number强制性的.
这非常有效.我的问题是,这UserViewModel WorkPhone是强制性的,而HomePhone不是.
无论如何我可以通过在Require属性中PhoneViewModel设置任何属性来减少HomeWork属性吗?
我试过这个:
[ValidateInput(false)]
Run Code Online (Sandbox Code Playgroud)
但它只适用于类和方法.
码:
public class UserViewModel
{
[Required]
public string Name { get; set; }
public PhoneViewModel HomePhone { get; set; }
[Required]
public PhoneViewModel WorkPhone { get; set; }
}
public class PhoneViewModel
{
public string CountryCode { get; set; } …Run Code Online (Sandbox Code Playgroud) c# asp.net-mvc validationattribute data-annotations asp.net-mvc-3
我想创建自定义客户端验证器,但我希望通过业务逻辑层的Data Annotations属性定义验证规则.如何在运行时访问模型验证属性?
我想写'generator',它会转换这段代码:
public class LoginModel
{
[Required]
[MinLength(3)]
public string UserName { get; set; }
[Required]
public string Password { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
进入这一个:
var loginViewModel= {
UserName: ko.observable().extend({ minLength: 3, required: true }),
Password: ko.observable().extend({ required: true })
};
Run Code Online (Sandbox Code Playgroud)
但当然不是来自.cs来源.=)
也许反思?
UPD
我发现了这个方法:MSDN.但无法理解如何使用它.
我创建了一个针对类的自定义ValidationAttribute.每当我尝试调用Validator.TryValidateObject时,这都会正确验证.但是当我在类中的属性中有其他ValidationAttribute时,验证结果不包含类级别验证的结果.
这是一个示例代码:
[AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = true)]
public class IsHelloWorldAttribute : ValidationAttribute
{
public object _typeId = new object();
public string FirstProperty { get; set; }
public string SecondProperty { get; set; }
public IsHelloWorldAttribute(string firstProperty, string secondProperty)
{
this.FirstProperty = firstProperty;
this.SecondProperty = secondProperty;
}
public override bool IsValid(object value)
{
PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(value);
string str1 = properties.Find(FirstProperty, true).GetValue(value) as string;
string str2 = properties.Find(SecondProperty, true).GetValue(value) as string;
if (string.Format("{0}{1}", str1,str2) == "HelloWorld")
return true;
return …Run Code Online (Sandbox Code Playgroud) 我有一个自定义 TagHelper,它扩展了 OOTB InputTagHelper。我根据与其关联的模型属性上存在的自定义 ValidationAttribute 有条件地向其添加属性。TagHelper.Process方法中的代码工作正常:
if (this.For.Metadata.ValidatorMetadata.OfType<NumericValidationAttribute>().Any())
{
output?.Attributes.SetAttribute(new TagHelperAttribute("inputmode", "numeric"));
output?.Attributes.SetAttribute(new TagHelperAttribute("pattern", "[0-9]*"));
}
Run Code Online (Sandbox Code Playgroud)
我的问题是在单元测试中。我使用 Net Core MVC 测试存储库中提供的代码编写了其他单元测试:https : //github.com/aspnet/Mvc/blob/master/test/Microsoft.AspNetCore.Mvc.TagHelpers.Test/
...但没有真正指导如何为我要测试的属性创建Forie ModelExpression,该属性具有与之关联的 Validation 属性:例如
public class TestModel
{
[NumericValidation(ErrorMessage = "Error message")]
public string Field1 { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
我希望能够填充For.Metadata.ValidatorMetadata此 ModelExpression的列表,但我不知道如何。
不起作用的完整单元测试是:
[Fact]
public void CustomInputTagHelperProcess_NumericValidationAttributeOnModelProperty_GeneratesCorrectHtml()
{
// Arrange
var metadataProvider = new EmptyModelMetadataProvider();
var htmlGenerator = new TestableHtmlGenerator(metadataProvider);
var model = new TestModel
{
Field1 = "cc", …Run Code Online (Sandbox Code Playgroud) unit-testing validationattribute asp.net-core-mvc asp.net-core-tag-helpers
我通过复制ASP.NET MVC 3 CompareAttribute创建了一个自定义CompareLessThan验证属性,而不是检查是否相等,我检查一个属性是否小于另一个属性.如果存在客户端错误,则向用户显示消息"{0}必须小于{1}".
我的模型设置如下,Display属性引用资源文件.
[CompareLessThan("AmountAvailable", ErrorMessageResourceName="CompareLessThan", ErrorMessageResourceType = typeof(Resources.ValidationMessages))]
[Display(Name = "Amount", ResourceType = typeof(Resources.Labels))]
public decimal Amount { get; set; }
[Display(Name = "AmountAvailable", ResourceType = typeof(Resources.Labels))]
public decimal AmountAvailable { get; set; }
Run Code Online (Sandbox Code Playgroud)
然后自定义验证GetClientValidationRules方法与CompareAttribute完全相同
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
yield return new ModelClientValidationLessThanRule(FormatErrorMessage(metadata.DisplayName), FormatPropertyForClientValidation(OtherProperty), this.AllowEquality);
}
Run Code Online (Sandbox Code Playgroud)
在这里,我们生成错误消息,如果出现问题,将显示给用户.我可以从资源文件中获取使用我的自定义CompareLessThan属性修饰的属性的显示名称,但我的问题是如何获取我们正在比较的"其他"属性的显示名称?在IsValid方法中,我们引用了validationContext,我可以从中为'other'属性生成PropertyInfo对象,我想获取显示名称.但是,在GetClientValidationRules中,我没有访问权限.
我总是可以为另一个属性的显示名称传递另一个值,但我希望有一种方法可以派生它,因为我已经用数据注释指定它.
有任何想法吗?
validation asp.net-mvc client-side-validation validationattribute
asp.net-mvc ×7
c# ×7
validation ×3
razor ×2
annotations ×1
asp.net ×1
regex ×1
unit-testing ×1