-1

I have an if statement to check whether there is at least 15 characters before the textarea is considered valid in my form. I don't mind users adding whitespace but, I don't want it to count as part of the length for the value.

if(userApplying.value.length <= 14){
     document.getElementById("applying_error").innerHTML = 
     "* please enter at least 15 characters in your message."
     error = true;
}//end of if

Answer in Javascript please.

websiteninja
  • 36
  • 1
  • 4
  • 1
    when you say 'whitespace' do you mean all `space` characters? or just carriage returns (`enter`s)? does " test string with spaces " = "test string with spaces" or "teststringwithspaces" for your desired result? – haxxxton May 15 '14 at 04:33
  • Strip whitespace, count what remains: `userApplying.value.replace(/\s/g,'').length`. There are minor differences in what `\s` matches between browsers, but it shouldn't matter for this. – RobG May 15 '14 at 04:36

1 Answers1

0

You can use the String.replace() function in conjunction with a regular expression to create a new variable that is equivalent to the original input but with the spaces removed, and then use that for your test:

var inputWithSpacesRemoved = originalInput.replace(/\s*/g, '');
if (isNormalizedInputValid(inputWithSpacesRemoved)) {
  // ...
}

In the above, I'm assuming you've tidied up things a little bit:

var isNormalizedInputValid = function(normalizedInput) {
  return normalizedInput.length < 15;
};

And:

var originalInput = userApplying.value;
Michael Aaron Safyan
  • 93,612
  • 16
  • 138
  • 200