Validate if aTextBox Value Start with a Specific Letter
Posted
by Vincent Maverick Durano
on Geeks with Blogs
See other posts from Geeks with Blogs
or by Vincent Maverick Durano
Published on Tue, 01 Feb 2011 16:32:15 GMT
Indexed on
2011/02/01
23:26 UTC
Read the original article
Hit count: 273
In case you will be working on a page that needs to validate the first character of the TextBox entered by a user then here are two options that you can use:
Option 1: Using an array
1: <asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" runat="server">
2: <script type="text/javascript">
3: function CheckFirstChar(o) {
4: var arr = ['A', 'B', 'C', 'D'];
5: if (o.value.length > 0) {
6: for (var i = 0; i < arr.length; i++) {
7: if (o.value.charAt(0) == arr[i]) {
8: alert('Valid');
9: return true;
10: }
11: else {
12: alert('InValid');
13: return false;
14: }
15: }
16: }
17: }
18: </script>
19: </asp:Content>
20: <asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
21: <asp:TextBox ID="TextBox1" runat="server" onblur="return CheckFirstChar(this);"></asp:TextBox>
22: </asp:Content>
The example above uses an array of string for storing the list of characters that a TextBox value should start with. We then iterate to the array and compare the first character of TextBox value to see if it matches any characters from the array.
Option 2: Using Regular Expression (Preferred way)
1: <asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" runat="server">
2: <script type="text/javascript">
3: function CheckFirstChar(o) {
4: pattern = /^(A|B|C|D)/;
5: if (!pattern.test(o.value)) {
6: alert('InValid');
7: return false;
8: } else {
9: alert('Valid');
10: return true;
11: }
12: }
13: </script>
14: </asp:Content>
15: <asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
16: <asp:TextBox ID="TextBox1" runat="server" onblur="return CheckFirstChar(this);"></asp:TextBox>
17: </asp:Content>
The example above uses regular expression with the pattern /^(A|B|C|D)/. This will check if the TextBox value starts with A,B,C or D. Please note that it's case sensitive. If you want to allow lower case then you can alter the patter to this /^(A|B|C|D)/i. The i in the last part will cause a case-insensitive search.
That's it! I hope someone find this post useful!
© Geeks with Blogs or respective owner