At the one end of my web application I have a database table storing a load of pieces of text.
In the middle I have an API that separates my application tiers.
At the other end I have a user interface consisting of many TextBoxes (or input type=text form elements, if you prefer).
I need the maxlength properties of the TextBoxes to be the same as the maximum string lengths in the various related database table columns. I would also like to do string length validation on my API.
Of course I can achieve this manually, but does anyone know of a technique on any platform that can assist in setting up any part of this automatically?
In my scenario I am using ASP.NET 3.5 WebForms, LINQ to SQL and SQL Server 2005.
At risk of not answering the question at all…
You seem to have a business rule that says ‘this particular field should contain a maximum of N characters.’
I would argue that both the database column’s size and the textbox maximum length are separate consequences of this business rule. Fixing one from the other confuses correlation with causation.
In addition, enforcing this business rule by examining the maximum length of the database column has other effects:
you’ll hit the database every time for what could otherwise be an in-memory validation operation;
if your business rule changes slightly (eg: N goes from 100 to 80 characters) then you need a schema-level change;
some databases working with variable-length character encoding like UTF8 only fuzzily define how many characters even fit in a given column;
more broadly, you’re coupling the business rule to an implementation artifact – what if you later decide to use an object database?
I’m not suggesting that you don’t sensibly size your database columns (you should), only that you decouple the business rule from the database implementation. If you can get away with a simple fixed-length-check in the application code, I would suggest that.
Edit having read your question a little more carefully, for your text field maximum lengths you need N ahead of validation. Nonetheless, this is still a business rule – can you write a
MaximumLengthattribute for your field accessors and interrogate that?