如何在 ASP.NET 文本框中强制输入大写?

发布于 2024-07-07 10:30:05 字数 258 浏览 8 评论 0原文

我正在编写一个 ASP.NET 应用程序。 我的网络表单上有一个文本框,我想强制用户输入的所有内容均为大写。 我想在前端做这个。 您还应该注意,此文本框上有一个验证控件,因此我想确保该解决方案不会干扰 ASP.NET 验证。

澄清: CSS 文本转换似乎使用户输入以大写形式显示。 然而,在幕后,由于验证控制失败,它仍然是小写。 您会看到,我的验证控件检查是否输入了有效的状态代码,但是我使用的正则表达式仅适用于大写字符。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(21

酒废 2024-07-14 10:30:05

为什么不结合使用 CSS 和后端呢? Use:

style='text-transform:uppercase' 

在文本框中,以及在代码隐藏中 use:

Textbox.Value.ToUpper();

您还可以轻松更改验证器上的正则表达式以使用小写和大写字母。 这可能是比强制使用大写更简单的解决方案。

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.

安人多梦 2024-07-14 10:30:05

在文本框上使用 CSS 样式。 你的 CSS 应该是这样的:

.uppercase
{
    text-transform: uppercase;
}

<asp:TextBox ID="TextBox1" runat="server" Text="" CssClass="uppercase"></asp:TextBox>;

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>;
皓月长歌 2024-07-14 10:30:05
**I would do like:
<asp:TextBox ID="txtName" onkeyup="this.value=this.value.toUpperCase()" runat="server"></asp:TextBox>**
**I would do like:
<asp:TextBox ID="txtName" onkeyup="this.value=this.value.toUpperCase()" runat="server"></asp:TextBox>**
我要还你自由 2024-07-14 10:30:05

好的,经过测试,这是一个更好、更干净的解决方案。

$('#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);

});

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);

});
零時差 2024-07-14 10:30:05

您可以拦截按键事件,取消小写事件,并将其大写版本附加到输入中:

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;
        }
    }
};

这适用于 Firefox 和 Internet Explorer。 您可以在此处查看其实际效果。

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.

披肩女神 2024-07-14 10:30:05
<!-- 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>
<!-- 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>
日久见人心 2024-07-14 10:30:05

我使用一个简单的内联语句

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

如果你不想使用CSS类,你可以只使用内联样式语句。(这个只是明显地变成大写):)

在服务器端使用

string UCstring = txtName.Text.ToUpper();

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();
天涯沦落人 2024-07-14 10:30:05

文本转换
CSS 属性指定如何将元素的文本大写。 它可用于使文本以全大写或全小写形式显示

CssClass

WebControl.CssClass 属性,

您可以了解更多相关信息 - 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


使用 Style="text -transform: uppercase;"CssClass="upper"

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"

风和你 2024-07-14 10:30:05
 style='text-transform:uppercase'
 style='text-transform:uppercase'
草莓酥 2024-07-14 10:30:05

我今天刚刚做了类似的事情。 这是修改后的版本:

<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>

基本上,脚本附加了一个在文本框失去焦点时触发的事件。

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.

待"谢繁草 2024-07-14 10:30:05

我会使用 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>

您必须在 /script 文件夹中包含 jQuery 库。

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.

戴着白色围巾的女孩 2024-07-14 10:30:05

我对四个流行的浏览器版本对这个问题做了一些分析。

  1. 样式标签简单地以大写形式显示字符,但是控制值仍然保留为小写
  2. 使用上面显示的字符代码的按键功能有点令人担心,因为在 Firefox chrome 和 safari 中,它禁用了 Ctrl + V 进入控件。
  3. 使用字符级别为大写的另一个问题也不是将整个字符串转换为大写。
  4. 我找到的答案是在 keyup 上结合 style 标签来实现这一点。

    <-- 表单名称=“frmTest”--> 
      <-- input type="text" size=100 class="ucasetext" name="textBoxUCase" id="textBoxUCase" --> 
      <-- /表格--> 
    
      窗口.onload = 函数() { 
          var input = document.frmTest.textBoxUCase; 
          输入.onkeyup = 函数() { 
              input.value = input.value.toUpperCase(); 
          } 
      }; 
      

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();
        }
    };
    
归属感 2024-07-14 10:30:05

将文本框上的样式设置为 text-transform:大写

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

栀子花开つ 2024-07-14 10:30:05

在前端使用文本转换 CSS,然后在验证之前在字符串服务器端使用 toUpper 方法。

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

淑女气质 2024-07-14 10:30:05

CSS 在这里可能会有所帮助。

style="text-transform: uppercase";"

这有帮助吗?

CSS could be of help here.

style="text-transform: uppercase";"

does this help?

谷夏 2024-07-14 10:30:05

这是一个对我有用的解决方案。

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

您必须从 < 获取 JavaScript a href="http://plugins.jquery.com/files/jquery.bestupper.min.js.txt" rel="nofollow">http://plugins.jquery.com/files/jquery.bestupper.min。 js.txt 就可以了。

奇迹般有效!

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!

痴意少年 2024-07-14 10:30:05

我意识到有点晚了,但我找不到与 ASP.NET AJAX 一起使用的好答案,所以我修复了上面的代码:

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;
    }

像这样使用:

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

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>
隔岸观火 2024-07-14 10:30:05

JavaScript 具有字符串的“toUpperCase()”函数。

所以,沿着这些思路:

function makeUpperCase(this)
{
    this.value = this.value.toUpperCase();
}

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

So, something along these lines:

function makeUpperCase(this)
{
    this.value = this.value.toUpperCase();
}
记忆里有你的影子 2024-07-14 10:30:05
  <telerik:RadTextBox ID="txtCityName" runat="server" MaxLength="50" Width="200px"
                            Style="text-transform: uppercase;">
  <telerik:RadTextBox ID="txtCityName" runat="server" MaxLength="50" Width="200px"
                            Style="text-transform: uppercase;">
难忘№最初的完美 2024-07-14 10:30:05
     $().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);
        }

这是一种可重用的方法。 任何数量的文本框都可以通过这种方式完成,无需命名。
通过更改 docReady 中的选择器可以实现页面范围的解决方案。

我的示例使用失去焦点,问题在输入时没有指定。 如果这在您的场景中很重要,您可以触发更改。

     $().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.

心作怪 2024-07-14 10:30:05

最少 8 个字符 至少 1 个字母和 1 个数字

有效密码示例:pass1234 OR PaSs1234 OR PASS1234

至少 8 个字符 至少 1 个字母、1 个数字和 1 个特殊字符

有效密码示例:pass@123 或 PaSS#123 或 PASS@123

至少 8 个字符,至少 1 个大写字母、1 个小写字母和 1 个数字

有效密码示例:PaSs1234 或 pASS1234

至少 8 个字符,至少 1 个大写字母、1 个小写字母、1 个数字和 1 个特殊字符 <

asp:TextBox ID="txtPolicy4" runat="server">

有效密码示例:PaSs@123 或 pAss@123

最少 8 个、最多 10 个字符 至少 1 个大写字母、1 个小写字母、1 个数字和 1 个特殊字符


有效密码示例:PaSs@123

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文