[英]Restrict single and double quotes in textbox in ASP.NET
我想限制單引號和雙引號以輸入到Asp.net中的文本框。 我該如何實現? 我如何驗證文本框?
您是否使用AjaxControlToolkit? 如果是這樣,則使用它。
<asp:TextBox runat="server" ID="TextBox1" Width="100px" />
<cc1:FilteredTextBoxExtender FilterMode="InvalidChars" ID="ftbe_TextBox1" runat="server"
TargetControlID="TextBox1" InvalidChars=""'" />
其中:cc1是AjaxControlToolkit的TagName
如果沒有,請手動進行
<asp:TextBox runat="server" ID="TextBox1" Width="100px" onkeypress="return restrictQuotes(event);" />
<script type="text/javascript">
function restrictQuotes(evt) {
var keyCode = evt.which ? evt.which : evt.keyCode;
return (keyCode != '"'.charCodeAt() && keyCode != "'".charCodeAt());
}
</script>
我將使用javascript
對文本框onchange
事件進行實時驗證。 然后,您可以在server-side
使用string.contains()
方法進行server-side
驗證。
您可以添加RegularExpressionValidator
並設置ValidationExpression
='^ [^ \\“] * $'以限制引號輸入
你可以用JavaScript做到
<script type="text/javascript">
function fixit() {
var numberOfElements = document.theForm.elements.length;
for (x=0; x<numberOfElements; x++) {
// replace all the single, double quotes:
var curElement = window.document.theForm.elements[x];
curElement.value = curElement.value.replace(/\'/g, "'");
curElement.value = curElement.value.replace(/\"/g, """);
}
return true;
}
</script>
然后以表格形式編寫
<form name='theForm' onSubmit='return fixit()'...
此代碼將循環所有元素。 如果要驗證單個元素,則可以阻止用戶編寫這些字符
在文本框中,您可以執行以下操作:
<input type="text" name="foo" onkeypress="return fix(event);">
在javascript中:
<script type="text/javascript">
function fix(e)
{
if(e.charCode == 34|| e.charCode == 39)
{
return false;
}
return true;
}
</script>
最后一部分阻止用戶編寫引號和雙引號。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.