我有这个代码试图验证它,但无法这样我希望它看起来像这个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() + "-";
答案 0 :(得分:0)
如果您希望客户端功能添加破折号,您可以执行以下操作。
<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;