Another common validation task that can be more successful if implemented on the client is the length restriction of inputs. Off the bat, we have this handy property in an order textbox.
<asp:TextBox ID="TextBox1" runat="server" MaxLength="256" />
The rendering engine would produce:
<input name="TextBox1" type="text" maxlength="256" id=" TextBox1" />
This is all well and good if we use our textbox just the way it is. But hilarity would soon ensue once we start adding this property if we wanted to render a text area.
<asp:TextBox ID="TextBox1" runat="server" MaxLength="256" TextMode="MultiLine" />
Corresponding output would be:
<textarea name="ctl00$TextBox1" rows="2" cols="20" id=" TextBox1"></textarea>
Not only MaxLength="256" wouldn’t work anymore but it’s completely gone. The first HTML was an input form with type=”Text” and the latter was a textarea form element. Maximum length appears not to be a native property of a textarea.
I’ve developed a short client-side script (because I enjoy churning these out) to help in validation of text input lengths applicable to both single and multi-line text fields.
var maxCharacters = 256;
var withinCharacterLimit = true;
var ValidateTB = document.getElementById(TB.id);
if (ValidateTB.value.length > maxCharacters)
withinCharacterLimit = false;
} return withinCharacterLimit;
The script is attempting to return the cursor (via the focus()) function back to the textfield once the input exceeds the desired maximum length which is 256 characters. Hooking this up to the input form elements, we take advantage of the onKeyUp and the onKeyDown client-side events of keyboard events.
TextBox1.Attributes["onKeyUp"] = "return checkCharacterLimit(this);";
TextBox1.Attributes["onKeyDown"] = "return checkCharacterLimit(this);";