tags:

views:

2153

answers:

3
+1  Q: 

Text Mask c#

Hi All

I need to validate a certain property to one of my classes. When I set the property, the class should validate the input and if incorrect, set the object to an invalid state.

Question : The property value must be in a certain mask/format eg. &&&&-&&&&-&&&&. I cannot use regular expressions. Is it possible to validate text against a mask value ?

Thanks

A: 

Is it possible to validate text against a mask value ?

Of course it's possible, in that you could write a function to take a string and a mask and check one against another.

So I'm unclear on what you're asking - are you asking if there are functions in the standard .Net libraries to do this? Or asking for an implementation of a mask-validation function? Or something else?

If you're looking for something in the library to help, MaskedTextProvider would probably do it, although it's overkill.

Paul
My question is then, are there built in .net functionality to take the string and validate it against the mask?
MegaByte
@Shaun - yes: Regex!
Marc Gravell
I edited my answer to add a pointer to a (rather more than you really need) function that should do that.
Paul
Thanks paul - The thing is, i store the format of the property in the db(whether its a mask or regex string). The gui controls and the bo validation will need to validate agains this format. If controls could use regex expressions, that would work fine...
MegaByte
controls cannot use regexps??
Vinko Vrsalovic
What is your GUI written in? Look at MaskedTextBox, it sounds like it may do exactly what you want
Paul
+2  A: 

Regular expressions are often over-used, but this is a pretty good example of when a regex is ideal... so: why can't you use them here?

Marc Gravell
My Business Object returns the format/mask to the ui via a property. The control in the ui then validates against that format. But I want my validation rules in my BO as well. So I would like the ui controls and my BO to use the format/maks in order to do the validation. Does this help?
MegaByte
That doesn't explain why you can't use regex. You might have to write a small function to convert your mask to regex string.
GeekyMonkey
@Shaun - you could store 2 masks (one regex, one for the UI) - not ideal. Alternatively, just have the UI ask the BO whether the property is valid - IDataErrorInfo is good for that, and is supported automatically for controls like DataGridView
Marc Gravell
@Shaun - GeekyMonkey's idea of converting the (generally simpler) UI mask to a regex by simple translation is a good one.
Marc Gravell
I like the translation function. Sounds good. Ill see what I can do.
MegaByte
A: 

Without regexp you have to write your own validation code, which checks the mask.

gerleim