New line characters in text area increases text length in C#

后端 未结 2 750
无人及你
无人及你 2021-01-04 19:37

I have this problem in my asp.net mvc application.

In one of my model there is a field \"Description\". The database column for this fields is set to NVarchar(

2条回答
  •  伪装坚强ぢ
    2021-01-04 19:58

    After taking a closer look at the solution by @Chris, I found that this would cause an endless loop for any control other than textarea with the @maxlength attribute.
    Furthermore, I found that using value (=the value of the textarea passed into the validator) would already have the leading and trailing line breaks cut off, which means the database operation still failed when it tried to save text containing those line breaks.
    So here is my solution:

    (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);
    

    I tested this in Chrome and a few IE versions and it worked fine for me.

提交回复
热议问题