簡體   English   中英

禁止在文本框中輸入無效字符列表的自定義驗證屬性

[英]Custom Validation Attribute that Prohibits Input of a list of invalid characters in textbox

我是一名正在使用 Asp.net MVC 的大學生,我需要進行自定義驗證,以防止輸入特定字符,例如 @#$%* 等特定字段。 我知道自定義驗證有點麻煩,但這部分任務需要這樣做。 我不介意我用一根手指打字,但是大學把學習任何編程主題或語言的所有樂趣都帶走了,因為我不能花太多時間來學習熟練的概念實現。 在這種情況下,自定義驗證。

我已經創建了一個 InvalidCharsAttribute Class 並且已經將必要的字段添加到必要的 class 中,如下所示...

InvalidCharsAttribute.cs

using System.ComponentModel.DataAnnotations;


namespace EnrollmentApplication.Models
{
    public class InvalidCharsAttribute : ValidationAttribute

    {
        readonly string invalidChars;

        public InvalidCharsAttribute(string invalidChars)
        {
            this.invalidChars = invalidChars;
        }

        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            if (value != null)
            {
                if ((string)value == invalidChars)
                {

                 return new ValidationResult("Notes contains unacceptable characters");


                }
            }

            return ValidationResult.Success;
        }
    }

要檢查無效字符的字段

 [InvalidChars(@"[*&%#@$^!]", ErrorMessage = "*&%#@$^! are invalid characters")]
        public virtual string Notes { get; set; }

我知道if ((string)value == invalidChars)是錯誤的,我只是不確定如何重寫/添加代碼以便我的自定義驗證有效。 最簡單的解決方案會很棒。

您可以使用 Regex 實現通過正則表達式驗證您的字符串。 如果您要比較的字符串與任何無效字符匹配,則響應將大於零,在這種情況下,您的代碼應返回 false:

    Regex.Matches(yourstring,@"[a-zA-Z]").Count;

編輯后的代碼如下:

    if (value != null)
        {
            if (Regex.Matches(((string)value),@"[*&%#@$^!]").Count > 0)
            {

             return new ValidationResult("Notes contains unacceptable characters");

            }
        }

試一試,Regex 實現可能會幫助您進行驗證。

問候,

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM