Don*_*Box 1 c# asp.net-core-mvc
如何使表单名字输入字段不接受带有空格字符的空字符串 " "
<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>
Run Code Online (Sandbox Code Playgroud)
模型:
public class ContactInfo
{
[Required(ErrorMessage = "This field is required")]
[StringLength(50)]
[DisplayName("First name")]
public string FirstName { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
使用[Required]属性,用户仍然可以提交一个只有空格字符的字符串" "
我知道这是一个简单的问题,但我是 ASP.NET MVC 的新手
用法:
[NotNullOrWhiteSpaceValidator]
public string FirstName { get; set; }
Run Code Online (Sandbox Code Playgroud)
如何制作自己的属性:
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.");
}
}
Run Code Online (Sandbox Code Playgroud)
这里还有一堆:https : //github.com/srkirkland/DataAnnotationsExtensions/tree/master/DataAnnotationsExtensions