Hiten Hiten - 1 month ago 6
jQuery Question

JQuery space validation

I am using Jquery custom validation for no space.

jQuery.validator.addMethod("noSpace", function(value, element) {
return value.indexOf(" ") < 0 ;
});


And its working fine.
But it also fire validation when I used space between the word like
"Test Example".

Example 1 :: " " //Validation (Its fine.)
Example 2 :: "Test Example" //Validation (I dont want validation in it.)

Basically I don't want a space in a starting but requrired space between the word.

Answer

I think you can use trim(). I'm not pretty sure about the validator, but you can try this:

jQuery.validator.addMethod("noSpace", function(value, element) { 
      return (value.trim() == value) && (value.indexOf(" ") > 0);
});

Edit: the correct answer:

jQuery.validator.addMethod("noSpace", function(value, element) { 
      return (value.trim() == value) && (value.indexOf(" ") < 0); 
})