Mahendra Pumbhadiya
Mahendra Pumbhadiya

Reputation: 290

Jquery validation code for not allowed only blank space in textbox

i m looking for code in which for not allowed only blank space... for e.g i have one textbox and i have tried this

$(document).ready(function()
{  
   $("#mybutton").live('click',function() 
   {
     var txt_family_name=$("#mytextbox").val();
     if(txt_family_name =="" || txt_family_name ==null)
     {
       alert("null"); 
     }
     else
     {
       alert("not null");
     }
   });
});

this above code i have tried and its not working. so pls help me on that.. on one of my button i m calling this above code

Example : space....with any text -- output should be not null : space space.... any space without any other text -- output should be null

Upvotes: 1

Views: 13926

Answers (5)

ashwini
ashwini

Reputation: 375

//To add method to remove blankspaces

$.validator.addMethod("blankSpace", function(value) { 
  return value.indexOf(" ") < 0 && value != ""; 
});

Upvotes: 0

Amul
Amul

Reputation: 159

Jquery Validation : require method only check the length of the input. So it allow the blank space.The solution will be the simple change the one line code in it.

required: function( value, element, param ) {

        // Check if dependency is met
        if ( !this.depend( param, element ) ) {
            return "dependency-mismatch";
        }
        if ( element.nodeName.toLowerCase() === "select" ) {

            // Could be an array for select-multiple or a string, both are fine this way
            var val = $( element ).val();
            return val && val.length > 0;
        }
        if ( this.checkable( element ) ) {
            return this.getLength( value, element ) > 0;
        }
        return value.length > 0;
    }

in above code change value.length to $.trim(value).length so simply remove the blank space

Upvotes: 1

Richard-Xie
Richard-Xie

Reputation: 1

you can use regexp.

$(document).ready(function() {
  $("#mybutton").bind('click', function() {
    var txt_family_name = $("#mytextbox").val();
    if (txt_family_name.replace(/\s/g, '') == "") {
      alert("null");
    } else {
      alert("not null");
    }
  });
});

Upvotes: 0

Reena
Reena

Reputation: 1119

See the updated code it's working

$(document).ready(function()
{  
$("#clickme").on('click',function() 
{
  var txt_family_name=$.trim($("#mytextbox").val());
 if(txt_family_name ==="" || txt_family_name ===null)
 {
   alert("null"); 
 }
 else
 {
   alert("not null");
 }
});
});

Upvotes: 1

Arpita Shekhar
Arpita Shekhar

Reputation: 73

you can use the length attribute and the trim method to remove the trailing spaces, if any: 

$("#mybutton").on('click',function() 
   {
     var length = $.trim($("#mytextbox").val()).length;
     if(length == 0)
     {
       alert("null"); 
     }
     else
     {
       alert("not null");
     }
   });

Upvotes: 2

Related Questions