【问题标题】:How to avoid multiple ifelse statements when validating user input? [Web Forms]验证用户输入时如何避免多个 ifelse 语句? [网络表格]
【发布时间】:2022-01-28 04:05:18
【问题描述】:

我有一个非常基本的注册页面,其中包含“电子邮件”、“密码”、“用户名”等文本框字段。 虽然我已经使用了客户端验证器(例如 asp:RegularExpressionValidator),但我还希望有一个强大的服务器端验证。但到目前为止,我只为一个文本字段得到了这个:

if(username.Contains(" ") || string.IsNullOrEmpty(password)) 
{
    //error: invalid username
}
else if (username.length<8)
{
   //error: username cannot be shorter than 8 characters
}
else if (username.length>30)
{
   //error: username cannot be longer than 30 characters
}
else if (IsUsernameTaken(username))
{
   //error: this username has already been taken by someone else
}
else if (something)
{
    //some error
}
//etc etc

有没有更好(和更有效)的方法来验证我的控件而不使用上述代码?

编辑:我正在使用 Asp.net Web 表单

【问题讨论】:

  • 您没有提到您使用的是哪种 ASP.NET 风格(WebForms、传统 MVC,更现代的东西)。他们中的大多数都有基于属性的验证(通常使用System.ComponentModel.DataAnnotations 中的属性)。看看:docs.microsoft.com/en-us/aspnet/mvc/overview/older-versions/…
  • @Flydog57 对不起,我忘了提。我使用的是 ASP.NET WebForms
  • WebForms 自诞生之日起(大约 20 年前)就得到了很好的验证。如果我没记错的话,您可以让它将匹配的客户端脚本注入您的页面。看看docs.microsoft.com/en-us/previous-versions/aspnet/…

标签: c# asp.net validation server-side code-behind


【解决方案1】:

我不知道您是否使用 MVC,但是是的,有。你真的不想验证你的“控件”,你想验证模型/视图模型。当用户提交表单时,您应该将提交的数据反序列化为您自己的模型/视图模型类。在创建该视图模型的类的声明中,您可以使用DataAnnotations 告诉框架每个字段的要求。像这样的:

using System.ComponentModel.DataAnnotations;
using ExpressiveAnnotations.Attributes; // this is a non-standard library

namespace MyProject.Models.ViewModels.Workorder
{
    public class CreateBillableUnbillableProjectViewModels
    {
        public class CreateBillableUnbillableProject : IValidatableObject
        {
            [Required]
            public string Title { get; set; }

            [Display(Name = "Proposed Budget")]
            [AssertThat("ProposedBudget > 0", ErrorMessage = "You must enter a value greater than 0")]
            [Required]
            [UIHint("String")]
            [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = Settings.DataFormatStringCurrency)]
            public decimal ProposedBudget { get; set; }
        }
    }
}

注意方括号中的标记。这些是DataAnnotations。此外,模型/视图模型作为一个整体可以被赋予必须有效的规则。例如,如果PropertyA 必须大于PropertyB。这就是上面的类实现IValidatableObject 的原因。像这样的:

        public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
        {
            //TODO: any other validation before changing and saving this record?

            if (PropertyA <= PropertyB)
                yield return new ValidationResult($"PropertyA must be greater than PropertyB", new[] { "PropertyA" });

            var db = new MyProjectEntities();

            if (db.WorkOrders.Any(i => i.Title == Title))
                yield return new ValidationResult($"A WorkOrder with the same title already exists.", new[] { "Title" });
        }

当您在控制器操作中执行 if (ModelState.IsValid) 时,会触发上述所有内容(属性级别验证和模型级别验证)。

见: https://docs.microsoft.com/en-us/aspnet/core/mvc/models/validation?view=aspnetcore-6.0

【讨论】:

  • 我忘了提到我正在使用 WebForms。很抱歉
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-07-28
  • 2013-11-02
  • 1970-01-01
相关资源
最近更新 更多