2010-09-06 71 views
0

林在asp.net MVC应用程序的工作这是在MVC 1做......所以验证了做以下的nerd dinner 1.0 tutorialasp.net的MVC 1.0验证

我刚刚定义的规则是这样

public bool Is_CellPhone(string val)   
     { 
      Regex celular = new Regex("^04[12][246][0-9]{7}$"); 
      return celular.IsMatch(val); 
     } 

在我GetRuleValidations我做这个

if (!Is_CellPhone(Celular)) 
        yield return new RuleViolation("El celular no cumple el formato", 

"Celular"); 

的问题是..当用户犯规提交值验证方法运行反正不需要手机等等,并返回一个错误,因为空字符串...我能做些什么来正确地防止这个错误?

回答

1

如果字符串为null或空就返回true:

public bool Is_CellPhone(string val)   
     { 
      if (string.IsNullOrEmpty(val)) { return true; } 
      Regex celular = new Regex("^04[12][246][0-9]{7}$"); 
      return celular.IsMatch(val); 
     } 

我怀疑你也可以在正则表达式覆盖这一点,但我在正则表达式吸所以我不会假装给意见那里。

+0

我猜这是有效的,但你需要为每个自定义规则做这些......这是一种毫无意义的规则验证应该只在提交值时运行 – ignaciofuentes 2010-09-06 20:10:48