gpt4 book ai didi

c# - 自动验证文本框设置破折号(-)

转载 作者:太空宇宙 更新时间:2023-11-03 14:56:16 25 4
gpt4 key购买 nike

我有这个代码我试图验证它但无法所以我希望它看起来像这样 12-12345-1-1 当用户在文本框中键入它应该能够是否可以通过 C#j-query

自动获取破折号
<asp:TextBox ID="txtNum" runat="server" placeholder="number" class="form-control" OnTextChanged="txtNum_TextChanged1" ></asp:TextBox>
<asp:RegularExpressionValidator ID="regxNum" ValidationExpression="\d{3}\d{3}\d{4}" runat="server" ErrorMessage="Invalid Num#" ControlToValidate="txtNum" ForeColor="Red"></asp:RegularExpressionValidator>

C#

if ((txtNum.Text.ToString().Length == 2) || (txtNum.Text.ToString().Length == 5) || (txtNum.Text.ToString().Length == 1))
txtNum.Text = txtNum.Text.ToString() + "-";

最佳答案

如果你想让客户端函数添加破折号,你可以这样做。

<asp:TextBox ID="TextBox1" runat="server" MaxLength="12"></asp:TextBox>

<script type="text/javascript">
$('#<%= TextBox1.ClientID %>').keydown(function () {
var txt = $(this).val();
if (txt.length === 2 || txt.length === 8 || txt.length === 10) {
$(this).val(txt += "-");
}
});
</script>

C# 的例子应该是这样的

//source string
string input = "12-12-3451-1";

//remove wrong dashes first
input = input.Replace("-", "");

//loop all characters in the string, doing this in a loop prevents index out of range
//exception when string it shorter that 9
for (int i = 0; i < input.Length; i++)
{
//insert the appropriate dashes
if (i == 2 || i == 8 || i == 10)
{
input = input.Insert(i, "-");
}
}

//show results
Label1.Text = input;

关于c# - 自动验证文本框设置破折号(-),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48894423/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com