There may come a time when you want to match a Regular Expression against a
string and you don't necessarily want or need to use one of the built in ASP.Net
Regular Expression Validators. For instance, using a validator, if the match
doesn't occur, you are not allowed to submit your form data. But, let's say, you
want to validate the data, but you don't really mind if the data is a match or
not and you merely want to send the user a message that the data didn't match
the correct format.
Using the System.Text.RegularExpressions Namespace (don't forget to
import it!), you can accomplish this in code. Note the following function:
Function RegExMatch(sItem as String, sRegEx as String) as Boolean
Dim r As Regex = New Regex(sRegEx)
Dim m As Match = r.Match(sItem)
Return m.Success
End Function
Here, we're taking the first argument in the function (sItem) and
matching it against the Regular Expression, which is in the second argument.
Since the Function returns a boolean, naturally, the only two possibilites are
TRUE or FALSE.
So, to implement this in code, let's create a scenario where you are entering
parts into your online system. For the partnumber itself, you use the format:
####.## - where all characters must be numeric. The Regular Expression for this
would be:
^[1-9][0-9][0-9][0-9]\.[0-9][0-9]
So, in your code, you can do something like this:
if RegExMatch(txtPartNum.text, "^[1-9][0-9][0-9][0-9]\.[0-9][0-9]") ="False" then
lblError.Text+="Part # must be in ####.## format"
'do other processing
Else
'do whatever processing you need here
End If
That's all there is to it. As you can see, with ASP.Net, it using validation
with Regular Expressions is much simpler than it sounds
No comments:
Post a Comment