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

Jigar Jain
  • 1,447
  • 1
  • 15
  • 38
  • 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. – oxygen Apr 25 '13 at 11:05
  • I would strongly recommend you not to use client-side input filtering, it is extremely bad practice, and easily bypassed. – Pfft Apr 25 '13 at 11:13
  • @JimmyvanBeele, why is it bad practice to validate inputs on the client side? – Derek Henderson Apr 25 '13 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. – Pfft Apr 25 '13 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. – Derek Henderson Apr 25 '13 at 11:20
  • @DerekHenderson If I interpreted his post right, he is planning on only using client-side filtering; I was merely stating _that_ is bad practice. – Pfft Apr 25 '13 at 11:22
  • I never said i wont be validating it on server..i definately will. Also CSS with ellipsis will hide by content(i guess) which i dont want to.. So javascript validation is required to me – Jigar Jain Apr 25 '13 at 11:36
  • @Jigar, should a url be prefixed with (http|https|ftp):// or would 'stackoverflow.com' pass validation? – Derek Henderson Apr 25 '13 at 12:19

7 Answers7

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
  }
}
MMeersseman
  • 2,541
  • 1
  • 13
  • 8
  • 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 – Jigar Jain Apr 25 '13 at 11:44
  • 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. – MMeersseman Apr 25 '13 at 12:01
  • 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 – Jigar Jain Apr 25 '13 at 12:18
  • 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 – Jigar Jain Apr 25 '13 at 12:23
  • Change this: t.match(wordLengthRegex) To this: !t.match(wordLengthRegex) – MMeersseman Apr 25 '13 at 12:34
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])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5]))|(([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=])*)(:\d*)?)(\/(([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)*)*|(\/((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)+(\/(([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)*)*)?)|((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)+(\/(([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)*)*)|((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)){0})(\?((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|[\uE000-\uF8FF]|\/|\?)*)?(\#((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|\/|\?)*)?$/i . test( this ) ) {
      alert( this + ' is an URL' );
    } else {
      alert( this + ' is not an URL' );
    }
  }
});

http://jsfiddle.net/vVYAp/

Pfft
  • 857
  • 6
  • 8
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;
};
Derek Henderson
  • 9,388
  • 4
  • 42
  • 71
  • 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 ? – Jigar Jain Apr 25 '13 at 13:10
  • 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 Jain Apr 25 '13 at 13:35
  • @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. – Derek Henderson Apr 25 '13 at 13:37
  • or better i will show it myself how i am doing :) gimme some time – Jigar Jain Apr 25 '13 at 13:37
  • @Jigar, I've edited my answer to supply a possible regex for `reURL`, but you can use whatever pattern you feel is best. – Derek Henderson Apr 25 '13 at 13:42
  • i have marked ur answer as correct. Because i think your code should work. it isnt working in my case maybe cause of some stupid error from myside.. thanks anyways :) – Jigar Jain Apr 25 '13 at 13:46
  • Object [object Array] has no method 'each' is what i get on running this http://jsfiddle.net/K8u5q/ – Jigar Jain Apr 25 '13 at 14:00
  • 1
    @Jigar, the stupid error was from me, not you. ;) The edited code now works. – Derek Henderson Apr 25 '13 at 14:12
  • haha okk.. But most below answers had did the same previous way so i thought it must work that way.. any ways thanks a lot :) – Jigar Jain Apr 25 '13 at 14:41
0

try this

    var value = Your text;

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

if(value.length == result .length)
  //not valid
else
 //valid
PSR
  • 39,804
  • 41
  • 111
  • 151
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/

Adil Shaikh
  • 44,509
  • 17
  • 89
  • 111
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");
Brainfeeder
  • 2,604
  • 2
  • 19
  • 37
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/

Chris Andersson
  • 1,291
  • 11
  • 16
  • 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. – Chris Andersson Apr 25 '13 at 12:14