简体   繁体   中英

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.

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); 
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM