34

I'm writing an ASP.NET application. I have a textbox on a webform, and I want to force whatever the user types to upper case. I'd like to do this on the front end. You should also note that there is a validation control on this textbox, so I want to make sure the solution doesn't interfere with the ASP.NET validation.

Clarification: It appears that the CSS text transform makes the user input appear in uppercase. However, under the hood, it's still lower case as the validation control fails. You see, my validation control checks to see if a valid state code is entered, however the regular expression I'm using only works with uppercase characters.

9
  • 1
    Are you intentionally limiting your regex to only working with uppercase characters? By your wording it sounds like you might not be aware that regex implementations typically support a case-sensitive switch.
    – J c
    Oct 14, 2008 at 19:27
  • I'm not a regex expert. I know of know way to support both upper and lower case State code comparisions in the regex beside duplicating every state code twice (upper and lower). I thought it would be cleaner just converting the input box to uppercase.
    – Aheho
    Oct 14, 2008 at 19:37
  • 4
    No worries - I'd recommend using something like the following (C#) instead of modifying the user input though: Regex re = new Regex("myExpression", RegexOptions.IgnoreCase);
    – J c
    Oct 17, 2008 at 11:57
  • I have the same exact problem. I am setting text-transform as uppercase to set the appearance of the textbox as the user types, and I'm using the onblur event to set the value to uppercase once the textbox loses focus. The validator however isn't happy with the value. Had you found a solution to this problem?
    – Fikre
    Mar 18, 2010 at 20:49
  • why not provide a dropdown for statecode instead?
    – RandomUs1r
    Sep 17, 2014 at 17:10

21 Answers 21

58

Why not use a combination of the CSS and backend? Use:

style='text-transform:uppercase' 

on the TextBox, and in your codebehind use:

Textbox.Value.ToUpper();

You can also easily change your regex on the validator to use lowercase and uppercase letters. That's probably the easier solution than forcing uppercase on them.

3
  • 3
    I'd go with ToUpper(). Why would you want to enforce such restrictions on the end-user? That's not a friendly UI. Take whatever the user gives you and make it upper case yourself.
    – Kon
    Oct 14, 2008 at 21:36
  • I would do this too. Messing around in Javascript until you have what you want is much more work, and you require Javascript to be enabled which is simply unnecessary with Rorschach's solution.
    – Rob
    Sep 7, 2010 at 11:35
  • Current property to use with "ToUpper()" method is "Text" instead of "Value", so you must use TextBox.Text.ToUpper();. Jun 22, 2021 at 14:17
25

Use a CSS style on the text box. Your CSS should be something like this:

.uppercase
{
    text-transform: uppercase;
}

<asp:TextBox ID="TextBox1" runat="server" Text="" CssClass="uppercase"></asp:TextBox>;
1
  • 3
    The REGEX validator will still fail with a purely CSS solution. Oct 14, 2008 at 21:37
10
**I would do like:
<asp:TextBox ID="txtName" onkeyup="this.value=this.value.toUpperCase()" runat="server"></asp:TextBox>**
9

Okay, after testing, here is a better, cleaner solution.

$('#FirstName').bind('keyup', function () {

    // Get the current value of the contents within the text box
    var val = $('#FirstName').val().toUpperCase();

    // Reset the current value to the Upper Case Value
    $('#FirstName').val(val);

});
1
  • There is problem with this solution if user completes writing the input and then thinks about editing. If use corrects and retypes a character then the cursor is again set to end of the string as value to textbox is reassinged.
    – Nikhil
    Aug 20, 2018 at 9:11
6

You can intercept the key press events, cancel the lowercase ones, and append their uppercase versions to the input:

window.onload = function () {
    var input = document.getElementById("test");

    input.onkeypress = function () {
        // So that things work both on Firefox and Internet Explorer.
        var evt = arguments[0] || event;
        var char = String.fromCharCode(evt.which || evt.keyCode);

        // Is it a lowercase character?
        if (/[a-z]/.test(char)) {
            // Append its uppercase version
            input.value += char.toUpperCase();

            // Cancel the original event
            evt.cancelBubble = true;
            return false;
        }
    }
};

This works in both Firefox and Internet Explorer. You can see it in action here.

1
  • 6
    But it doesn't work if the user tries to type in the middle of the text.
    – erikkallen
    Sep 27, 2009 at 16:37
4
<!-- Script by hscripts.com -->
<script language=javascript>
    function upper(ustr)
    {
        var str=ustr.value;
        ustr.value=str.toUpperCase();
    }

    function lower(ustr)
    {
        var str=ustr.value;
        ustr.value=str.toLowerCase();
    }
</script>

<form>
    Type Lower-case Letters<textarea name="address" onkeyup="upper(this)"></textarea>
</form>

<form>
    Type Upper-case Letters<textarea name="address" onkeyup="lower(this)"></textarea>
</form>
3

I use a simple one inline statement

<asp:TextBox ID="txtLocatorName" runat="server"
 style="text-transform:uppercase" CssClass="textbox"  
 TabIndex="1">
</asp:TextBox>

If you don't want to use css classes you can just use inline style statement.(This one just visibly make uppercase) :)

On Server side use

string UCstring = txtName.Text.ToUpper();
3
  • 1
    This answer has been supplied and the reason why it's not sufficient is explained in the question.
    – EWit
    Jun 19, 2014 at 6:47
  • 1
    It's fine. Somebody else can benefit with this. Although I don't think it should be accepted. Jun 19, 2014 at 6:55
  • 1
    text-transform only changes the appearance, it doesn't force the underlying value to uppercase.
    – Aheho
    Jun 19, 2014 at 12:25
3

text-transform CSS property specifies how to capitalize an element's text. It can be used to make text appear in all-uppercase or all-lowercase

CssClass

WebControl.CssClass Property

you can learn more about it - https://developer.mozilla.org/en/docs/Web/CSS/text-transform

https://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.webcontrol.cssclass(v=vs.110).aspx


use Style="text-transform: uppercase;" or CssClass="upper"

2
  • Where? How does it help? Any reference?
    – dakab
    Jun 22, 2016 at 7:36
  • You probably wouldn’t have posted this as an answer if it didn’t work for you. However, where exactly did you place these attributes? How did you learn of text-transform or CssClass? You could improve your answer by adding information like this.
    – dakab
    Jun 22, 2016 at 8:23
2
 style='text-transform:uppercase'
1
  • 1
    text-transform only changes the appearance, it doesn't force the underlying value to uppercase
    – Aheho
    Jun 22, 2016 at 18:21
2

I just did something similar today. Here is the modified version:

<asp:TextBox ID="txtInput" runat="server"></asp:TextBox>
<script type="text/javascript">
    function setFormat() {
        var inp = document.getElementById('ctl00_MainContent_txtInput');
        var x = inp.value;
        inp.value = x.toUpperCase();
    }

    var inp = document.getElementById('ctl00_MainContent_txtInput');
    inp.onblur = function(evt) {
        setFormat();
    };
</script>

Basically, the script attaches an event that fires when the text box loses focus.

5
  • I don't get this. Where did you get the id 'ctl00_MainContent_txtInput' from?
    – Aheho
    Oct 15, 2008 at 1:25
  • ASP.NET translates your IDs. You can figure them out by viewing the source of the page you are working with. ctl00 is the generic prefix (but it can be different), MainContent just happened to be the name of the Form that the control was placed in.
    – Jason Z
    Oct 15, 2008 at 3:36
  • 1
    Couldn't this potentially break when moving to a newer version of ASP.NET?
    – Aheho
    Oct 15, 2008 at 11:55
  • 1
    Possibly, but you could always use a unique text box name and a JavaScript framework like jQuery and find the control where the unique name matches a pattern. I was trying to keep the sample code simple.
    – Jason Z
    Oct 15, 2008 at 12:54
  • 6
    There's a better way to get the client id -> <%= TextBox1.ClientID %>. That would render the correct ID. Aug 28, 2009 at 4:52
2

I would do this using jQuery.

<script src="Scripts/jquery-1.3.2.js" type="text/javascript"></script>
<script type="text/javascript">
    $(document).ready(function() {
        $("#txt").keydown(function(e) {
            if (e.keyCode >= 65 & e.keyCode <= 90) {
                val1 = $("#txt").val();
                $("#txt").val(val1 + String.fromCharCode(e.keyCode));
                return false;
            }
        });
    });
</script>

You must have the jQuery library in the /script folder.

1
  • 2
    except for when you're typing in the middle of the text Mar 7, 2012 at 21:48
2

I have done some analysis about this issue on four popular browser versions.

  1. the style tag simple displays the characters in uppercase but, the control value still remains as lowercase
  2. the keypress functionality using the char code displayed above is a bit worry some as in firefox chrome and safari it disables the feature to Ctrl + V into the control.
  3. the other issue with using character level to upper case is also not translating the whole string to upper case.
  4. the answer I found is to implement this on keyup in conjunction with the style tag.

    <-- form name="frmTest" -->
    <-- input type="text" size=100 class="ucasetext" name="textBoxUCase" id="textBoxUCase" -->
    <-- /form -->
    
    window.onload = function() {
        var input = document.frmTest.textBoxUCase;
        input.onkeyup = function() {
            input.value = input.value.toUpperCase();
        }
    };
    
1

Set the style on the textbox as text-transform: uppercase?

1
  • Read the clarification in the question itself. That only changes the appearance but not the underlying value in the textbox.
    – Aheho
    Aug 31, 2011 at 17:26
1

Use the text-transform CSS for the front-end and then use the toUpper method on your string server-side before you validate.

1
  • The validation control that's failing runs client-side.
    – Aheho
    Oct 14, 2008 at 19:39
1

CSS could be of help here.

style="text-transform: uppercase";"

does this help?

1
  • 1
    text-transform only changes the appearance, it doesn't force the underlying value to uppercase
    – Aheho
    Jun 22, 2016 at 18:20
1

here is a solution that worked for me.

http://plugins.jquery.com/project/bestupper

You have to get the JavaScript from http://plugins.jquery.com/files/jquery.bestupper.min.js.txt and there you go.

Works like a charm!

0

I realize it is a bit late, but I couldn't find a good answer that worked with ASP.NET AJAX, so I fixed the code above:

function ToUpper() {
        // So that things work both on FF and IE
        var evt = arguments[0] || event;
        var char = String.fromCharCode(evt.which || evt.keyCode);

        // Is it a lowercase character?
        if (/[a-z]/.test(char)) {
            // convert to uppercase version
            if (evt.which) {
                evt.which = char.toUpperCase().charCodeAt(0);
            }
            else {
                evt.keyCode = char.toUpperCase().charCodeAt(0);
            }
        }

        return true;
    }

Used like so:

       <asp:TextBox ID="txtAddManager" onKeyPress="ToUpper()" runat="server" 
             Width="84px" Font-Names="Courier New"></asp:TextBox>
1
0

JavaScript has the "toUpperCase()" function of a string.

So, something along these lines:

function makeUpperCase(this)
{
    this.value = this.value.toUpperCase();
}
5
  • That will only change it after, no as they type it. Oct 14, 2008 at 19:02
  • You could append this function to the onchange event of the text area and it would update it on the fly, though it would be a little bit slow. CSS is the way to go IMHO.
    – Tom
    Oct 14, 2008 at 19:20
  • 2
    @diodeus - if you use TextChange event then it'll occur as they top. @Tom - does the CSS actually change the underlying ASCI or just how it's displayed? Oct 14, 2008 at 20:10
  • 1
    @Stephen - That's a really good question! I created a small page to test this out and it appears that CSS only changes the way that it appears not the underlying ASCII.
    – Tom
    Oct 14, 2008 at 21:18
  • 1
    @Tom - That's what I thought, as such, it needs to occur via JS rather than CSS in order for the validator to fire correctly Oct 14, 2008 at 21:36
0
  <telerik:RadTextBox ID="txtCityName" runat="server" MaxLength="50" Width="200px"
                            Style="text-transform: uppercase;">
0
     $().ready(docReady);

     function docReady() {

            $("#myTextbox").focusout(uCaseMe);
     }

     function uCaseMe() {

            var val = $(this).val().toUpperCase();

            // Reset the current value to the Upper Case Value
            $(this).val(val);
        }

This is a reusable approach. Any number of textboxes can be done this way w/o naming them. A page wide solution could be achieved by changing the selector in docReady.

My example uses lost focus, the question did not specify as they type. You could trigger on change if thats important in your scenario.

-1

Minimum 8 characters at least 1 Alphabet and 1 Number <asp:TextBox ID="txtPolicy1" runat="server"></asp:TextBox>
<asp:RegularExpressionValidator ID="Regex1" runat="server" ControlToValidate="txtPolicy1" ValidationExpression="^(?=.[A-Za-z])(?=.\d)[A-Za-z\d]{8,}$" ErrorMessage="Password must contain: Minimum 8 characters atleast 1 Alphabet and 1 Number" ForeColor="Red" />

Valid Password Examples: pass1234 OR PaSs1234 OR PASS1234

Minimum 8 characters at least 1 Alphabet, 1 Number and 1 Special Character <asp:TextBox ID="txtPolicy2" runat="server"></asp:TextBox>
<asp:RegularExpressionValidator ID="Regex2" runat="server" ControlToValidate="txtPolicy2" ValidationExpression="^(?=.[A-Za-z])(?=.\d)(?=.[$@$!%#?&])[A-Za-z\d$@$!%*#?&]{8,}$" ErrorMessage="Minimum 8 characters atleast 1 Alphabet, 1 Number and 1 Special Character" ForeColor="Red" />

Valid Password Examples: pass@123 OR PaSS#123 OR PASS@123

Minimum 8 characters at least 1 Uppercase Alphabet, 1 Lowercase Alphabet and 1 Number <asp:TextBox ID="txtPolicy3" runat="server"></asp:TextBox>
<asp:RegularExpressionValidator ID="Regex3" runat="server" ControlToValidate="txtPolicy3" ValidationExpression="^(?=.[a-z])(?=.[A-Z])(?=.*\d)[a-zA-Z\d]{8,}$" ErrorMessage="Password must contain: Minimum 8 characters atleast 1 UpperCase Alphabet, 1 LowerCase Alphabet and 1 Number" ForeColor="Red" />

Valid Password Examples: PaSs1234 OR pASS1234

Minimum 8 characters at least 1 Uppercase Alphabet, 1 Lowercase Alphabet, 1 Number and 1 Special Character

<asp:TextBox ID="txtPolicy4" runat="server"></asp:TextBox>
<asp:RegularExpressionValidator ID="Regex4" runat="server" ControlToValidate="txtPolicy4" ValidationExpression="^(?=.[a-z])(?=.[A-Z])(?=.\d)(?=.[$@$!%?&])[A-Za-z\d$@$!%?&]{8,}" ErrorMessage="Password must contain: Minimum 8 characters atleast 1 UpperCase Alphabet, 1 LowerCase Alphabet, 1 Number and 1 Special Character" ForeColor="Red" />

Valid Password Examples: PaSs@123 OR pAss@123

Minimum 8 and Maximum 10 characters at least 1 Uppercase Alphabet, 1 Lowercase Alphabet, 1 Number and 1 Special Character

<asp:TextBox ID="txtPolicy5" runat="server"></asp:TextBox>
<asp:RegularExpressionValidator ID="Regex5" runat="server" ControlToValidate="txtPolicy5" ValidationExpression="^(?=.[a-z])(?=.[A-Z])(?=.\d)(?=.[$@$!%?&])[A-Za-z\d$@$!%?&]{8,10}" ErrorMessage="Password must contain: Minimum 8 and Maximum 10 characters atleast 1 UpperCase Alphabet, 1 LowerCase Alphabet, 1 Number and 1 Special Character" ForeColor="Red" />

Valid Password Examples: PaSs@123

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.