英文:
ASP.NET character count of text box different than server side text box character count
问题
我有一个用于在页面上向用户显示剩余字符数量的JavaScript函数。
当我在服务器端验证长度以确保它不大于列长度之前插入到数据库时,我实际上得到了不同的计数。
在线研究显示,JavaScript与C#不同,它会以不同的方式计算换行符/回车符和可能的一些其他特殊字符。
有人有解决这个问题的方法吗?
这是我在客户端的JavaScript代码:
<script>
var textarea = document.getElementById('TxtComment');
window.onload = textareaLengthCheck();
function textareaLengthCheck() {
var maxChars = 4000;
var textArea = textarea.value.length;
var charactersLeft = maxChars - textArea;
var count = document.getElementById('cmt-characters-left');
count.innerHTML = "Characters left: " + charactersLeft + " of " + maxChars;
}
textarea.addEventListener('keyup', textareaLengthCheck, false);
textarea.addEventListener('keydown', textareaLengthCheck, false);
</script>
尝试添加这段代码,但似乎问题变得更糟:
var textArea = textarea.value.replace(/(\r\n|\n|\r)/g, "").length;
英文:
I have a javascript function to display the remaining character count to the user on the page.
When I validate the length server side prior to a database insert to make sure it is not greater than the column length I'm actually getting a different count.
Researching online it appears that javascript counts new lines / CR and maybe some other special characters differently than C# does.
Does anyone have a workaround for this?
This is my javascript on the client side:
<script>
var textarea = document.getElementById('TxtComment');
window.onload = textareaLengthCheck();
function textareaLengthCheck() {
var maxChars = 4000;
var textArea = textarea.value.length;
var charactersLeft = maxChars - textArea;
var count = document.getElementById('cmt-characters-left');
count.innerHTML = "Characters left: " + charactersLeft + " of " + maxChars;
}
textarea.addEventListener('keyup', textareaLengthCheck, false);
textarea.addEventListener('keydown', textareaLengthCheck, false);
</script>
Tried adding this - but it seemed to make the problem even worse:
var textArea = textarea.value.replace(/(\r\n|\n|\r)/g, "").length;
答案1
得分: 1
我已经弄清楚了。
Javascript将""\r\n"" 计为1个字符,而C#则计为2个字符。
在服务器端的C#验证中,我将它更改为:
TxtComment.Text = this.TxtComment.Text.Replace(""\\r\\n"", "\n");
if (this.TxtComment.Text.Trim().Length > 4000)
{
... 在此添加您的验证消息 ...
}
英文:
I figured it out.
Javascrit was counting the "\r\n" as 1 character, C# was counting as 2 characters.
On the server side C# validation I changed it to this:
TxtComment.Text = this.TxtComment.Text.Replace("\r\n", "\n");
if (this.TxtComment.Text.Trim().Length > 4000)
{
... your Validation message here ...
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论