Geek
Geek

Reputation: 3329

javascript validation for length with spaces

I have a functionality which calculates the length of the characters in text area as follows: JSP code:

<textarea class="textAreaLarge" id="citation" rows="20" cols="180" name="citation" maxlength="<%=maxCitationLength%>" onKeyUp="toCount(<%=maxCitationLength%>);"><%=citation%></textarea>
            <strong><div id="sBann" class="minitext"></div></strong>

JS is

function toCount(){
document.getElementById('citation').onkeyup = function () {
  document.getElementById('sBann').innerHTML = (characters - this.value.length) + " characters left.";
};
}

Say for example this is the content of the text area ignoring the quotes. This is a total of 10 characters excluding the quotes.

"test

1111"

javascript does it correctly. Say MaxLength is 1500 it says '1490 characters left'.

When the same validation is done again on the java side this is what the code does.

int maxCitationLength = utility.getMaxCitationLength(rec);
String txtCitation = myUtil.checkNull(citationForm.getValue("citation"));
if (txtCitation.length() > maxCitationLength) {
    request.setAttribute("error",
                         "The Citation field cannot be larger than " + maxCitationLength +
                         " characters.");
}

There is always a discrepancy between these 2 conditions. For example I typed 1500 characters including spaces in text area and the form says 0 characters left and doesnt let me type more. But when I submit servlet does the validation again and gets error saying field cannot be larger than 1500 characters.Constant value is same 1500. However I guess the space is calculated differently in java and javascript. What is the best way to do this? ANy suggestions please?

Upvotes: 2

Views: 661

Answers (1)

hthanguyen
hthanguyen

Reputation: 96

You are right, Spring MVC will convert LF = Line Feed, CR = carriage return to \r \n. I tried to reproduce on my code.

Text area in form Request param

So that my solution is that we will replace these characters with a space.

With Javascript:

someText = someText.replace(/(\n|\r)/g, " ");

With Java:

str = str.replaceAll(/(\n|\r)/g, " ")

Upvotes: 3

Related Questions