我有这是我的虚拟机:
[Display(Name = "Reason for Cancellation")]
[Required]
[StringLength(245)] // 245 characters to allow for History Type prefix to be added
public string CancelJustificationComments { get; set; }
我注意到,如果该值是一个空格列表,则上述验证将被忽略-显然是它的编码方式。
如何添加进一步的验证以修剪所有空格,以确保有一个“合法”值?
谢谢
答案 0 :(得分:1)
一种简单的方法是使用RegularExpressionAttribute
[Display(Name = "Reason for Cancellation")]
[Required]
[RegularExpression(@"\w")]
[StringLength(245)] // 245 characters to allow for History Type prefix to be added
public string CancelJustificationComments { get; set; }
此属性通常用于强制输入格式,使其Regex以^
开头并以$
结尾,以便检查完整的字符串。
使用\w
正则表达式,您无需检查字符串的开始或结束方式,只说需要至少一个“单词字符”([a-zA-Z0-9]
)
答案 1 :(得分:0)
class ActionsRegistry:
def __init__(self):
self._registry = {}
def __call__(self, func):
klass_name, func_name = func.__qualname__.rsplit('.', 1)
if klass_name not in self._registry:
self._registry[klass_name] = []
self._registry[klass_name].append(func)
return func
def __get__(self, obj, objtype=None):
if obj is None:
return self
return self._registry[objtype.__qualname__]
class Base:
actions = ActionsRegistry()
class Human(Base):
@Base.actions
def talk(self):
pass
class Dog(Base):
@Base.actions
def wuff(self):
pass
class Cat(Base):
@Base.actions
def miau(self):
pass
数据注释具有可选参数 [Required]
- 将其设置为 AllowEmptyStrings
将导致模型验证在空白字符串上失败。
false