You can certainly do something like the following:
private RegularExpressionValidator GetValidatorControl(string controlToValidate, string errorMessage)
{
RegularExpressionValidator validator = new RegularExpressionValidator();
validator.ID = String.Format("{0}RegExValidator", controlToValidate);
validator.ValidationExpression = @"^\$?[0-9]+(\.[0]{2})?$";
validator.ControlToValidate = controlToValidate;
validator.ErrorMessage = errorMessage;
return validator;
}
And, in the Page_Load event or similar, you can call it this way:
Page.Controls.AddAt(Page.Controls.IndexOf(AddHourlyRate) + 1, GetValidatorControl(control.ID, "my validation message"));
This will add the validator control to your page and your expression will only be defined here (it can be placed into another class as a static method and shared throughout the project).
You could also use the method in this Stack Overflow answer to get all of the RegEx validators on your page, and then set the ValidationExpression on each one. For example, if you wrap all of your controls in a Panel (with an ID of RootPanel in my example) or similar container control then you could just:
IEnumerable<Control> validators = RootPanel.FlattenChildren();
IEnumerator<Control> enumerator = validators.GetEnumerator();
while (enumerator.MoveNext() == true)
{
if (enumerator.Current is RegularExpressionValidator) //Only interested in RegularExpressionValidators. You could even filter this further by naming them consistently and checking for a fragment of the ID here.
{
((RegularExpressionValidator)enumerator.Current).ValidationExpression = @"^\$?[0-9]+(\.[0]{2})?$"; //Load from config if necessary!
}
}
To use the FlattenChildren method, place it into a public static class somewhere inside your project and reference it with the appropriate using directives. See this article for extension methods in .Net.
No matter what happens, you'll need one RegularExpressionValidator per control. Your other option, is, of course, to validate these manually yourself in javascript or on PostBack.
^\$?[0-9]+(\.[0]{2})?$) that I don't want to copy - I'd rather only this written in one place.