【发布时间】:2019-01-15 05:26:56
【问题描述】:
这是我的第一篇文章。
我需要如下所示的字符串数组验证。
[Required(ErrorMessage = "Content name is required")]
public string[] ContentName { get; set; }
我找到了a post which has the same situation。
This answer 和下面的代码对我帮助很大,我可以解决我的问题。
public class StringArrayRequiredAttribute : ValidationAttribute
{
protected override ValidationResult IsValid (object value, ValidationContext validationContext)
{
string[] array = value as string[];
if(array == null || array.Any(item => string.IsNullOrEmpty(item)))
{
return new ValidationResult(this.ErrorMessage);
}
else
{
return ValidationResult.Success;
}
}
}
还有
[StringArrayRequired(ErrorMessage = "Content name is required")]
public string[] ContentName { get; set; }
但现在我发现了另一个问题。此验证仅适用于服务器端。我希望我也可以进行客户验证。因为这会让我的客户更开心!!
那么你能给我一个好的方法吗?等待你的答案!!
感谢您的帮助。 在我看来,我写了一个简短的代码。
$.validator.addMethod('stringarrayrequired', function (value, element, params) {
let array = value;
if (array == null) {
return false;
}
for (var i = 0; i < array.length; i++) {
if (!array[i]) {
return false;
}
}
return true;
}, '');
$.validator.unobtrusive.adapters.add("stringarrayrequired", function (options) {
options.rules["stringarrayrequired"] = "#" + options.element.name.replace('.', '_'); // mvc html helpers
options.messages["stringarrayrequired"] = options.message;
});
(抱歉,我的 JS 不是很流利……) 我将 id="stringarrayrequired" 添加到我的 .但它不起作用。 我还检查了html代码。当我点击提交按钮时,“ContentName”的输入标签中应该有一个 class="input-validation-error" 或 "valid",但我找不到它们。
我还需要更多信息...有人帮忙吗?
我找到了解决问题的方法。
(我将属性名称 ContextName 更改为 Selection)
[Display(Name = "Selections")]
public Selection[] Selections { get; set; }
public class Selection
{
[Required(ErrorMessage = "SelectionItem is empty")]
public string SelectionItem { get; set; }
}
我将 Selections 用于 , SelectionItem 用于 和 。
如您所知,[必需] 属性不适用于字符串 []。所以我创建了一个 Selection 类并将 string[] 更改为 Selection[],并将 [Required] 属性应用于字符串。
我知道这不是一个干净的方法......我会使用万无一失的东西。
【问题讨论】:
-
您可以查看foolproof,它为您构建客户端,自定义验证。
-
我检查了链接,这似乎是解决我问题的好方法!!这在 ASP.NET Core 2.0 中有效吗??
-
是的,你可以使用它。
-
如果您想回答自己的问题,请不要在问题中包含答案。只需在页面底部添加您自己的答案即可。
标签: asp.net-mvc validation client-side