本文介绍了在客户端验证ASP.NET MVC中的字符串数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的第一篇文章.

我需要像下面这样的字符串数组验证.

  [必填(ErrorMessage =必填内容名")公共字符串[] ContentName {get;放;} 

我发现具有相同情况的帖子./p>

此答案和以下代码对我有很大帮助,我可以解决我的问题.

 公共类StringArrayRequiredAttribute:ValidationAttribute{受保护的重写ValidationResult IsValid(对象值,ValidationContextvalidationContext){string []数组=值作为string [];if(array == null || array.Any(item => string.IsNullOrEmpty(item))){返回新的ValidationResult(this.ErrorMessage);}别的{返回ValidationResult.Success;}}} 

还有

  [StringArrayRequired(ErrorMessage =需要内容名称")]公共字符串[] ContentName {get;放;} 

但是现在我发现了另一个问题.此验证仅在服务器端有效.我希望我也可以进行客户验证.因为这会让我的客户更快乐!

那么您能给我一个很好的方法吗?等待您的答案!


感谢您的帮助.我认为我写的是简短代码.

  $.validator.addMethod('stringarrayrequired',function(value,element,params){让数组=值;if(array == null){返回false;}for(var i = 0; i< array.length; i ++){如果(!array [i]){返回false;}}返回true;},'');$ .validator.unobtrusive.adapters.add("stringarrayrequired",函数(选项){options.rules ["stringarrayrequired"] =#" + options.element.name.replace('.','_');//mvc html助手options.messages ["stringarrayrequired"] = options.message;}); 

(对不起,我不太懂JS ...)然后将id ="stringarrayrequired"添加到我的.但这是行不通的.我还检查了html代码.当我单击提交"按钮时,"ContentName"的输入标记中应该有一个class ="input-validation-error"或"valid",但是我找不到它们.

我仍然需要更多信息...有人帮助吗?


我找到了解决问题的方法.

(我将属性名称ContextName更改为Selection)

  [Display(Name ="Selections")]public Selection []选择{放;}公共课选拔{[Required(ErrorMessage ="SelectionItem为空")公共字符串SelectionItem {get;放;}} 

我将Selections用于,SelectionItem用于和.

如您所知,[Required]属性不适用于string [].因此,我创建了一个Selection类,并将string []更改为Selection [],然后将[Required]属性应用于字符串.

我知道这不是一种干净的方法……我将使用万无一失的东西.

解决方案

在您的视图中添加以下 javaScript 代码:

  $.validator.addMethod('stringarrayrequired',function(value,element,params){//这里根据检查输入值返回true或false},'');$ .validator.unobtrusive.adapters.add("stringarrayrequired",函数(选项){options.rules ["stringarrayrequired"] =#" + options.element.name.replace('.','_');//mvc html助手options.messages ["stringarrayrequired"] = options.message;}); 

This is my first post.

I need string array validation such like below.

[Required(ErrorMessage = "Content name is required")]
public string[] ContentName { get; set; }

I found a post which has the same situation.

This answer and following code helped me so much and I could solve my problem.

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;
        }
    }
}

And

[StringArrayRequired(ErrorMessage = "Content name is required")]
public string[] ContentName { get; set; }

But now I found an another problem. This validation works only server side. I wish I could have a client validation too. Because it would make my client much happier!!

So would you give me a nice way for this? Waiting for your answers!!


Thank you for your help.I write a short code in my view.

$.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;
});

(Sorry, I'm not fluent in JS...)And I add id="stringarrayrequired" to my . But it doesn't work.I also checked html code. When I click the submit button, there should be a class="input-validation-error" or "valid" in input tag for "ContentName", but I couldn't find both of them.

I still need more info... Anyone help?


I found a way to solve my problem.

(I changed property name ContextName to Selection)

[Display(Name = "Selections")]
public Selection[] Selections { get; set; } 

public class Selection
{
    [Required(ErrorMessage = "SelectionItem is empty")]
    public string SelectionItem { get; set; }
}

I use Selections for , SelectionItem for and .

As you know, [Required] attribute doesn't work for string[]. So I created a Selection class and changed string[] to Selection[], and applied [Required] attribute to string.

I know that this's not a clean way... I'll use foolproof or something.

解决方案

Add the following javaScript code in your view:

$.validator.addMethod('stringarrayrequired', function (value, element, params) {
    // here return true or false based on checking the input value
},'');


$.validator.unobtrusive.adapters.add("stringarrayrequired", function (options) {
    options.rules["stringarrayrequired"] = "#" + options.element.name.replace('.', '_'); // mvc html helpers
    options.messages["stringarrayrequired"] = options.message;
});

这篇关于在客户端验证ASP.NET MVC中的字符串数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-23 11:02