gpt4 book ai didi

c# - 针对 MVC 中非必需属性的整数验证

转载 作者:太空狗 更新时间:2023-10-30 01:20:40 24 4
gpt4 key购买 nike

我正在尝试验证我拥有的模型的属性。此属性不是必需的,因此如果其无效的 MVC 似乎会忽略它。我什至创建了自定义 ValidationAttribute,但没有任何效果。

public class NumberWang : ValidationAttribute
{
public override bool IsValid(object value)
{
if (value == null)
return true;

int g;
if (int.TryParse(value.ToString(), out g))
{
if (g >= 0)
return true;
}
return false;
}
}

public class MyModel
{
[Range(0, 999999, ErrorMessage = "category_id must be a valid number")]
[NumberWang(ErrorMessage = "That's NumberWang!")]
public int? category_id { get; set; }

/* there are other properties of course, but I've omitted them for simplicity */

public void Validate()
{
Validator.TryValidateProperty(this.category_id,
new ValidationContext(this, null, null) { MemberName = "category_id" },
this.validation_results);
}
}

如果我将值“abc”作为 category_id 传递给该模型,它就可以正常验证。我究竟做错了什么?

最佳答案

我找到了一个丑陋的解决方法。

似乎如果 category_id 是可为 null 的 int? 而我的值不是有效数字,则会传递 null 值,并且模型不会看到无效的“abc”值。

[Range(0, 999999, ErrorMessage = "category_id must be a valid number")]
public int? category_id { get; set; }

// when we pass a good number
MyAction?category_id=123
validation: successful

// when we pass a bad number
// validation ignores it. not what we want.
MyAction?category_id=abc
validation: successful

如果我将 category_id 更改为不可为 null 的 int,即使未传递任何值,它也无法通过验证。

[Range(0, 999999, ErrorMessage = "category_id must be a valid number")]
public int? category_id { get; set; }

// when we pass a good number
MyAction?category_id=123
validation: successful

// when we pass an bad number
MyAction?category_id=abc
validation: "category_id must be a valid number"

// BUT, when we don't pass any number at all ...
MyAction
validation: "category_id must be a valid number"

丑陋的解决方法

如果我将 category_id 更改为 string,然后仅在需要时将其转换为 int,我可以仅使用 [范围]

[Range(0, 999999, ErrorMessage = "category_id must be a valid number")]
public string category_id { get; set; }

// when we pass a good number
MyAction?category_id=123
validation: successful

// when we pass a bad number
MyAction?category_id=abc
validation: "category_id must be a valid number"

// no number, no validation. hooray!
MyAction
validation: successful

它很丑陋,但它确实有效。

(注意:不需要自定义属性,所以我删除了它并只使用 [Range])

关于c# - 针对 MVC 中非必需属性的整数验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18334350/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com