Optional regex validation rule

Optional regex validation rule

Old forum URL: forums.lhotka.net/forums/t/1456.aspx


jwooley posted on Wednesday, October 11, 2006

In an old thread (http://forums.lhotka.net/forums/permalink/1596/1596/ShowThread.aspx#1596) the question was asked how would you validate a regular expression that was optional. By default the  RegExPatterns strings require the regex value. The response in that thread was to add the following to the regex string: |^[/S/s]{0,0}$.

I would like to propose an alternate change to the RegExMatch method itself. In my mind, evaluation of a required field should not be part of the RegEx evaluator. If you have a required field (string), check it with the StringRequired rule. Thus, I recommend changing RegExMatch as follows:

Public Function RegExMatch(ByVal target As Object, _
  
ByVal e As RuleArgs) As Boolean

   Dim CompareValue As String = _
     
CallByName(target, e.PropertyName, CallType.Get).ToString
  
If CompareValue = String.Empty Then Return True
   
  
Dim rx As Regex = DirectCast(e, RegExRuleArgs).RegEx
  
If Not rx.IsMatch(CompareValue) Then
     
e.Description = _
        
String.Format(My.Resources.RegExMatchRule, e.PropertyName)
     
Return False
  
Else
     
Return True
  
End If

End Function

With this implementation, we do not take the hit of regex evaluation if the value is an empty string.
What say ye?

Jim Wooley
http://devauthority.com/blogs/jwooley

jkellywilkerson replied on Wednesday, October 11, 2006

Hey Jim,

Yeah, you must have been posting as I was typing.  I have three fields that are not required, but if information is entered, it must match the format of the expression.  However, when I add the Regex Common Rule check for the fields, I get broken rules.

Has this always been the case, or is this something new?

Kelly.

jwooley replied on Wednesday, October 11, 2006

I am just starting to implement rules on a new CSLA 2.0 project so I can't say for sure, but I suspect that it has always been the case since it has to do with the RegEx.IsMatch method which doesn't know about optional values.
 
Jim Wooley
http://devauthority.com/blogs/jwooley
----- Original Message -----
From: jkellywilkerson
To: jimwooley@hotmail.com
Sent: Wednesday, October 11, 2006 4:34 PM
Subject: Re: [CSLA .NET] Optional regex validation rule

Hey Jim,

Yeah, you must have been posting as I was typing.  I have three fields that are not required, but if information is entered, it must match the format of the expression.  However, when I add the Regex Common Rule check for the fields, I get broken rules.

Has this always been the case, or is this something new?

Kelly.




Copyright (c) Marimer LLC