3

I have a form. I want to put validation so that It will check if user enters white spaces or not. If its white spaces then show error. How could I do this?

2
  • Did you try anything? Form validation is a common problem and there is a lot of information floating around. Did you run into a specific issue when trying to implement it? Commented Jul 11, 2012 at 9:26
  • Yes I want to validate whether user enters whitespace i.e. IF he enters several spaces then he still can be register which I do not want Commented Jul 11, 2012 at 9:51

4 Answers 4

10

In case you want to detect if there is any white space all through the user's input string,

var str = $("input").val();
if( str.indexOf(" ") !== -1 )
{
    alert("bad input");
}

Example: http://jsfiddle.net/pYquc/

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

2 Comments

I want whether user enters some string of abc. if he enter abc then it is fine. But if he enters several spaces then it should show an error.
jsfiddle.net/pYquc If he enters even a single space, it shows "bad input"
4

Use jQuery.trim(str) which remove the whitespace or tabs and you can validate.

http://api.jquery.com/jQuery.trim/

Comments

0
Try this usong javascript:
var v = document.form.element.value;
var v1 = v.replace("","");
if( v1.length == 0){
 alert("error");
}

OR you can use following functions:

 // whitespace characters
      var whitespace = " \t\n\r";

      /****************************************************************/

      // Check whether string s is empty.
      function isEmpty(s)
      { return ((s == null) || (s.length == 0)) }

      /****************************************************************/

      function isWhitespace (s)
      {
           var i;

           // Is s empty?
           if (isEmpty(s)) return true;

           // Search through string's characters one by one
           // until we find a non-whitespace character.
           // When we do, return false; if we don't, return true.

           for (i = 0; i < s.length; i++)
           {
                // Check that current character isn't whitespace.
                var c = s.charAt(i);

                if (whitespace.indexOf(c) == -1) return false;
           }

           // All characters are whitespace.
           return true;
      }

Comments

0
function doValidations(){
   if(jQuery.trim( $(".className").val())==""){
     alert("error message");
     return false;    
   }else{
     return true;
   }
}

<input type="submit" onclick="return doValidations();">

1 Comment

I am already doing this. But when user enters only spaces then it still can be register I do not want that

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.