Using data annotations for custom validation in ASP.NET MVC
Data annotations in ASP.NET MVC are powerful tools for validating user input. The StringLength
attribute allows validating the length of a single string attribute. But what if you need to verify the combined length of multiple properties?
To do this, implement a custom validation attribute.
<code class="language-csharp">public class CombinedMinLengthAttribute : ValidationAttribute { // 构造函数 } // 方法</code>
In custom attributes:
PropertyNames
Array holds the attribute names to be combined for length validation. IsValid
overridden method sums the length of the string attributes and compares it to MinLength
. To use custom properties, decorate the properties in your view model as follows:
<code class="language-csharp">public class MyViewModel { [CombinedMinLength(20, "Bar", "Baz", ErrorMessage = "组合长度必须超过20")] public string Foo { get; set; } }</code>
The above is the detailed content of How Can I Validate the Combined Length of Multiple Properties Using Custom Data Annotation in ASP.NET MVC?. For more information, please follow other related articles on the PHP Chinese website!