StringLength/Minlength 验证不会阻止用户发布没有值的表单 [英] StringLength/Minlength validation doesn't prevent user from posting the form with no value

查看:23
本文介绍了StringLength/Minlength 验证不会阻止用户发布没有值的表单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的 ViewModel 有以下属性

I have the following property on my ViewModel

[StringLength(20, MinimumLength = 1, ErrorMessageResourceName = "Error_StringLength", ErrorMessageResourceType = typeof(Global))]
public string LeagueName { get; set; }

如果字符串最终大于 20 个字符,则验证将触发并且不允许用户发布表单.但是,如果该字段为空,这意味着 LeagueName 属性的长度小于 1,它将允许用户发布表单.

If the string ends up being larger than 20 characters the validation will fire and not allow the user to post the form. However, if the field is blank, which means that the LeagueName property has a length of less than 1 it will allow the user to post the form.

我知道这可以通过使用 Required 属性轻松解决,但为什么在这种情况下验证没有按预期工作?

I know this is easily resolved by using the Required attribute, but why is the validation not working as expected in this scenario?

推荐答案

这是设计使然.

这是 StringLength 的验证逻辑:

This is the validation logic for StringLength:

public override bool IsValid(object value)
{
  this.EnsureLegalLengths();
  int num = value == null ? 0 : ((string) value).Length;
  if (value == null)
    return true;
  if (num >= this.MinimumLength)
    return num <= this.MaximumLength;
  else
    return false;
}

如您所见,当字符串为空时 StringLength 返回 true.

As you can see, when the string is null StringLength returns true.

这篇关于StringLength/Minlength 验证不会阻止用户发布没有值的表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆