我的 asp.net mvc 应用程序中有这个问题。
在我的一个模型中有一个字段“描述”。此字段的数据库列设置为 NVarchar(300)
。
在我看来,我正在创建一个文本区域,如下所示。
@Html.TextAreaFor(m => m.Description, new { maxlength = "300" })
我正在使用“jquery.validate.unobtrusive.min.js”进行客户端验证。因此,当用户在文本区域中键入内容长度超过 300 个字符时,它会显示消息“请输入不超过 300 个字符”。
一切正常,直到出现以下情况。 用户在文本区域中输入以下数据。
f
f
f
f
f
f
f
f
sdfa
(此内容有8行)
根据“非干扰性”验证,此内容的长度为 300 (将每个新行“\n”计为单个字符),因此验证通过并回发页面。
在我的 C# 代码中,由于编码,相同的内容变为长度 308 (将每个新行“\r\n”计为 2 个字符),这最终导致数据库操作失败,因为它只允许 300 个字符。
如果有人说我应该在这个特定属性上有 StringLength
属性,我有以下理由不拥有它。
如果我放置此属性,则此特定属性不会发生客户端验证,它会转到服务器,并且由于模型无效,它会返回带有错误消息的页面。
请告诉我可能的解决方案是什么?
最佳答案
仔细查看@Chris 的解决方案后,我发现这会导致除具有 @maxlength
属性的 textarea 之外的任何控件的无限循环。
此外,我发现使用value
(=传递给验证器的textarea的值)已经将前导和尾随换行符切断,这意味着数据库操作仍然失败它试图保存包含这些换行符的文本。
所以这是我的解决方案:
(function ($) {
if ($.validator) {
//get the reference to the original function into a local variable
var _getLength = $.validator.prototype.getLength;
//overwrite existing getLength of validator
$.validator.prototype.getLength = function (value, element) {
//double count line breaks for textareas only
if (element.nodeName.toLowerCase() === 'textarea') {
//Counts all the newline characters (\r = return for macs, \r\n for Windows, \n for Linux/unix)
var newLineCharacterRegexMatch = /\r?\n|\r/g;
//use [element.value] rather than [value] since I found that the value passed in does cut off leading and trailing line breaks.
if (element.value) {
//count newline characters
var regexResult = element.value.match(newLineCharacterRegexMatch);
var newLineCount = regexResult ? regexResult.length : 0;
//replace newline characters with nothing
var replacedValue = element.value.replace(newLineCharacterRegexMatch, "");
//return the length of text without newline characters + doubled newline character count
return replacedValue.length + (newLineCount * 2);
} else {
return 0;
}
}
//call the original function reference with apply
return _getLength.apply(this, arguments);
};
}
})(jQuery);
我在 Chrome 和几个 IE 版本中对此进行了测试,对我来说效果很好。
关于javascript - 文本区域中的新行字符增加了 C# 中的文本长度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11241076/