验证用户输入时如何避免多个ifelse语句?[Web 表单]

How to avoid multiple ifelse statements when validating user input? [Web Forms]

提问人:xandune 提问时间:1/28/2022 最后编辑:xandune 更新时间:1/28/2022 访问量:428

问:

我有一个非常基本的注册页面,其中包含“电子邮件”、“密码”、“用户名”等文本框字段。 虽然我已经使用了客户端验证器(例如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 表单

C# asp.net 验证 服务器端 代码隐藏

评论

1赞 Flydog57 1/28/2022
你没有提到你正在使用哪种风格的 ASP.NET(WebForms、传统的 MVC、更现代的东西)。它们中的大多数都具有基于属性的验证(通常使用 中的属性)。看一看: learn.microsoft.com/en-us/aspnet/mvc/overview/older-versions/...System.ComponentModel.DataAnnotations
0赞 xandune 1/28/2022
@Flydog57 对不起,我忘了提。我正在使用 ASP.NET WebForms
0赞 Flydog57 1/28/2022
自诞生以来(大约20年前),WebForms已经得到了很好的验证。如果我没记错的话,你可以让它将匹配的客户端脚本注入到你的页面上。看看 learn.microsoft.com/en-us/previous-versions/aspnet/...

答:

1赞 Jonathan 1/28/2022 #1

我不知道你是否在使用 MVC,但是是的,有。你并不是真的想验证你的“控件”,你想验证模型/视图模型。当用户提交表单时,您应该将提交的数据反序列化到您自己的 model/viewmodel 类中。在创建该视图模型的类的声明中,可以使用它来告诉框架每个字段的要求。像这样的东西: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; }
        }
    }
}

请注意方括号中的标记。这些是.此外,可以为整个模型/视图模型提供必须有效的规则。例如,if 必须大于 。这就是为什么上面的类实现 .像这样的东西:DataAnnotationsPropertyAPropertyBIValidatableObject

        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://learn.microsoft.com/en-us/aspnet/core/mvc/models/validation?view=aspnetcore-6.0

评论

0赞 xandune 1/28/2022
我忘了说我正在使用 WebForms。对不起