【问题标题】:Form validation of empty strings空字符串的表单验证
【发布时间】:2018-07-27 07:05:22
【问题描述】:

如何使表单名字输入字段不接受带有空格字符的空字符串" "

    <form asp-action="SaveRegistration" autocomplete="off">
        <div asp-validation-summary="ModelOnly" class="text-danger"></div>
        <div class="form-group">
            <label asp-for="FirstName" class="control-label"></label>
            <input asp-for="FirstName" class="form-control" />
            <span asp-validation-for="FirstName" class="text-danger"></span>
        </div>

型号:

public class ContactInfo
{
    [Required(ErrorMessage = "This field is required")]
    [StringLength(50)]
    [DisplayName("First name")]
    public string FirstName { get; set; }
}

使用[Required] 属性,用户仍然可以使用仅包含空格字符" " 的字符串提交

我知道这是一个简单的问题,但我是 ASP.NET MVC 的新手

【问题讨论】:

  • 你知道,你可以使用[StringLength] 和.. 是什么阻止你使用@Html.TextBoxFor()
  • @BagusTesa 我已经在使用 StringLength。 Html.TextBoxFor&lt;input asp-for="FirstName" 好多少?
  • @Bola MinLength 有什么帮助?我想阻止用户输入只有空格字符的字符串,我不想限制到最小长度
  • [Required(AllowEmptyStrings = false)] - 这行吗?听起来您可以使用 IsNullOrWhiteSpace 检查编写自定义 RequiredAttribute

标签: c# asp.net-core-mvc


【解决方案1】:

用法:

[NotNullOrWhiteSpaceValidator]
public string FirstName { get; set; }

如何制作自己的属性:

using System;
using System.ComponentModel.DataAnnotations;

public class NotNullOrWhiteSpaceValidatorAttribute : ValidationAttribute
{
    public NotNullOrWhiteSpaceValidatorAttribute() : base("Invalid Field") { }
    public NotNullOrWhiteSpaceValidatorAttribute(string Message) : base(Message) { }

    public override bool IsValid(object value)
    {
        if (value == null) return false;

        if (string.IsNullOrWhiteSpace(value.ToString())) return false;

        return true;        
    }

    protected override ValidationResult IsValid(Object value, ValidationContext validationContext)
    {
        if (IsValid(value)) return ValidationResult.Success;
        return new ValidationResult("Value cannot be empty or white space.");
    }
}

这里还有很多:https://github.com/srkirkland/DataAnnotationsExtensions/tree/master/DataAnnotationsExtensions

【讨论】:

  • 谢谢!这是服务器端验证,对吗?需要发布表单才能进行验证
  • 正确,许多人添加了客户端 JavaScript 验证,您应该始终进行服务器端验证,如图所示,在客户端浏览器(例如 Chrome 甚至 Nintendo Wii)上禁用 JavaScript。通常验证方法将通过控制器中的if (Model.IsValid) 调用。也可以在管道的早期调用这些验证...
【解决方案2】:

您始终可以使用regular expression

例如:

[RegularExpression(@".*\S+.*$", ErrorMessage = "Field Cannot be Blank Or Whitespace"))]
public string FirstName { get; set; }

【讨论】:

  • 不错。尽管正则表达式很讨厌。
  • 同理,它在 C# 端有效,但有时在 js 端却不行……看看后面。
  • @BagusTesa“有些人不会”?这甚至意味着什么?
  • @SBFrancies 我会将您的评论标记为答案,但是我正在寻找比 RegExp 更好的东西。这可以通过使用 ViewState.IsValid 或自定义客户端验证来避免
  • 谢谢 - 我同意,我个人不喜欢正则表达式。
【解决方案3】:

第一

你可以试试stringlength或者minlength数据标注

第二

你可以使用 parsley.js

这是一个很棒的客户端表单验证库。

我建议您同时使用客户端和服务器端验证。

【讨论】:

  • String Length 或 MinLength 不会阻止 whitespace.being 有效
【解决方案4】:

注意:这适用于 .net MVC 4+

里面有一个AllowEmptyStrings的实现 [Required(ErrorMessage = " is required.")].

如果允许空字符串,则此方法返回true;否则为假。此方法的默认值设置为 false。所以不用担心!测试和验证相同。它不应该允许单个或多个空字符串。如果没有明确地使它为假,看看它是否工作。

FYR` {

public class RequiredAttribute : ValidationAttribute
    {
        //
        // Summary:
        //     Initializes a new instance of the 
           System.ComponentModel.DataAnnotations.RequiredAttribute
        //     class.
        public RequiredAttribute();

        //
        // Summary:
        //     Gets or sets a value that indicates whether an empty string is 
       // allowed.
        //
        // Returns:
        //     true if an empty string is allowed; otherwise, false. The default 
        // value is false.
        public bool AllowEmptyStrings { get; set; }

        //
        // Summary:
        //     Checks that the value of the required data field is not empty.
        //
        // Parameters:
        //   value:
        //     The data field value to validate.
        //
        // Returns:
        //     true if validation is successful; otherwise, false.
        //
        // Exceptions:
        //   T:System.ComponentModel.DataAnnotations.ValidationException:
        //     The data field value was null.
        public override bool IsValid(object value);
    }

}`

【讨论】:

    【解决方案5】:

    默认行为是拒绝空字符串。您可以通过将 AllowEmptyStrings 设置为 true docs 来更改此行为

    [Required(ErrorMessage = "This field is required")]
    

    【讨论】:

      猜你喜欢
      • 2019-11-03
      • 2016-09-04
      • 1970-01-01
      • 1970-01-01
      • 2012-12-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多