0

I have a problem here with validating user's input in textarea. A user is suppose to enter his description in one of the textarea feild in form. But some people just put the random text like 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' or something to bypass the minimum length requirement.

Now i want to prevent user from typing such long text without any spaces since it disrupts the UI of my page. Also a long text entered by user without any spaces can be a valid url too. So how do i manage this & throw a error to user to correct the text only if it is too long and it isnt a valid url ??

PS: I dont want to split string myself.. I just want to detect it and throw error to user on client side validation. Just to put end to some doubts, i will do server side validation in which i will forcibly enter a space and save it in DB. But i am expecting to solve this problem on client side

8
  • Are you sure you are solving a real problem? How many users are actually doing it? And does it really matter? Try using CSS with overflow ellipsis. Commented Apr 25, 2013 at 11:05
  • I would strongly recommend you not to use client-side input filtering, it is extremely bad practice, and easily bypassed. Commented Apr 25, 2013 at 11:13
  • @JimmyvanBeele, why is it bad practice to validate inputs on the client side? Commented Apr 25, 2013 at 11:16
  • @DerekHenderson Because if someone is using NoScript, which comes with Tor, and it is also a widely used addon for Firefox, the validation will not work, and thus, the problem remains. It is also bad for security as a whole, since you get people trying to block SQL injections client-side. Commented Apr 25, 2013 at 11:18
  • @JimmyvanBeele, and if someone is using JS and you do all your validation on the server side, you've made needless server calls! Good practice is validating on both client and server sides. Commented Apr 25, 2013 at 11:20

7 Answers 7

2
var STRING_MAX_LENGTH = 10;

var description = 'aaa aaaaaaaaaa bbbbbbbbbb http://www.google.com/search?q=client-side-filtering';
var array = description.split( ' ' );

$.each( array, function() {
  if ( this.length >= STRING_MAX_LENGTH ) {
    if( /^([a-z]([a-z]|\d|\+|-|\.)*):(\/\/(((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:)*@)?((\[(|(v[\da-f]{1,}\.(([a-z]|\d|-|\.|_|~)|[!\$&'\(\)\*\+,;=]|:)+))\])|((\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\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. test( this ) ) {
      alert( this + ' is an URL' );
    } else {
      alert( this + ' is not an URL' );
    }
  }
});

http://jsfiddle.net/vVYAp/

Sign up to request clarification or add additional context in comments.

Comments

2
function validate()
{
  var expression = /[-a-zA-Z0-9@:%_\+.~#?&//=]{2,256}\.[a-z]{2,4}\b(\/[-a-zA-Z0-9@:%_\+.~#?&//=]*)?/gi;
  var wordLengthExpr = /\b[^\s]{50,}\b/;
  var regex = new RegExp(expression);
  var wordLengthRegex = new RegExp(wordLengthExpr);
  var t = $("#myTextarea").val();
  if (t.match(regex) ||  !t.match(wordLengthRegex))
  {
    //valid
  }
  else
  {
    //throw error
  }
}

5 Comments

Hii @MMeersseman. Could you please explian your Regex ?i tried but it gives me error even when i just enter 'aa' or 'ab' anything legal
I edited my post again, I made a mistake. It should work now. Basically you search for a word containing 10 or more non-whitespace characters. Let me know if you still have problems with it. You can change that '10' to whatever you feel suits your needs.
I tried but still it throws an error on even a single letter entered in textarea..I am calling the function validate on keyup event
in wordLengthExpr you are checking for minlength to be 10. But we are talking about max length without spaces.. i mean throwing error when user inputs a string with 50 characters entered without a space between them & those 50 chars arent URL
Change this: t.match(wordLengthRegex) To this: !t.match(wordLengthRegex)
1

This is a two step process:

  1. Determine if any words are too long.
  2. If so, determine if they are valid URLs.
var validateWordLength = function (str) {
    var maxLength = 50,  // or whatever max length you want
        reURL = /^(ftp|http|https):\/\/[^\s]+$/, // use whatever regular expression for URL matching you feel best
        words = str.split(/\s+/),
        i;

    for (i = 0; i < words.length; i += 1) {
        if (words[i].length > maxLength) {
            // test for url
            // but bear in mind the answer at http://stackoverflow.com/questions/1410311/regular-expression-for-url-validation-in-javascript
            // testing for url may not be fruitful
            if (!reURL.test(words[i])) {
                return false;
            }
        }
    }

    return true;
};

9 Comments

Your code seems good but if the words array has 3 values and if 2nd value sets valid = false, and 3rd value again sets valid = true, then after each function the valid = true will be returned which shouldnt be.. am i right ?
its okk..but am getting weird errors :( i feel like giving up this validation thing :( because when i wrote return false inside each function the netbeans shows error saying 'Anonymous function does not always return a value' :( It would be asking for too much but would be great if u can show a working demo on jsfiddle with textarea
@Jigar, remember that I did not define reURL, which is most likely why you're getting errors. You have to supply the RE for this to work. I could put one in there if you'd like.
or better i will show it myself how i am doing :) gimme some time
@Jigar, the stupid error was from me, not you. ;) The edited code now works.
|
0

try this

    var value = Your text;

    var result = value.replace(" ","");

if(value.length == result .length)
  //not valid
else
 //valid

Comments

0

You can get length of each word, and then can decide whether to allow the user or not -

var arr = text.split(' ');

$.each(arr,function(){
   console.log(this.length);
   // check valid word length
}); 

http://jsfiddle.net/mohammadAdil/cNZtn/

Comments

0

If you use the jQuery validate plugin you can add a method to it:

jQuery.validator.addMethod("samechars", function(value, element) { 
    return this.optional(element) ||  !/([a-z\d])\1\1/i.test(value); 
}, "Invalid input");

Comments

0

If you want to use jQuery you can use the following:

$("form").submit(function(e){
var $textarea = $('#msg'),
    maxWordLength = 20;

            var value = $textarea.val().split(' '),
                longWord = false;

            for(var n = 0; n < value.length; n++) {
                if(value[n].length >= maxWordLength)
                    longWord = true;
            }

if(longWord) {
    alert('Too long word');
    return false;
}
});

Here is a fiddle: http://jsfiddle.net/pJgyu/31286/

1 Comment

And of course can this be written with only javascript also, I had this function in a jquery project so this is my code from that project.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.