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, _ 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
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.
----- Original Message -----From: jkellywilkersonSent: Wednesday, October 11, 2006 4:34 PMSubject: Re: [CSLA .NET] Optional regex validation ruleHey 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