我有一个可选的字段,但如果它在那里,它必须正好是六个字符长。
StringLength Dataannotation 似乎不允许这样做。有什么方法可以组合事物以获得我想要的东西吗?我理论上可以使用正则表达式,但如果可能的话我想避免这种情况。
我有一个可选的字段,但如果它在那里,它必须正好是六个字符长。
StringLength Dataannotation 似乎不允许这样做。有什么方法可以组合事物以获得我想要的东西吗?我理论上可以使用正则表达式,但如果可能的话我想避免这种情况。
Use:
[StringLength(6, MinimumLength = 6)]
public string MyString { get; set; }
With this you're specifying a Maximum of 6 chars and a Minimum of 6 chars. If you enter something below 6, you'll get a message like this one when trying to post the data:
The field MyString must be a string with a minimum length of 6 and a maximum length of 6.
OR a Regular Expression:
[RegularExpression(@"^.{6,6}$")]
public string MyString { get; set; }
There's a way around this by implementing the IValidatableObject interface, but you'll lose the client side/unobtrusive validation. The validation will be done on the server side:
public class MyClass : IValidatableObject
{
public string MyString { get; set; }
// ... Other fields ...
public virtual IEnumerable<ValidationResult> Validate(
ValidationContext validationContext)
{
if (!String.IsNullOrEmpty(MyString))
{
if(MyString.Length != 6)
{
// ... Validation rules ...
yield return new ValidationResult("MyString must be 6 chars long",
new[] { "MyString" });
}
}
}
}