admin管理员组

文章数量:1321044

I want to validate text field using jauery in the following manner:

1. Text field take only 0-9 with only one decimal place;and

2. If amount enter in not in negative, put the negative symbol at the begging of digits entered!

$('[name="pm"]').keyup(function() {

    //?

 });

I want to validate text field using jauery in the following manner:

1. Text field take only 0-9 with only one decimal place;and

2. If amount enter in not in negative, put the negative symbol at the begging of digits entered!

$('[name="pm"]').keyup(function() {

    //?

 });
Share Improve this question edited Jun 15, 2012 at 11:29 T.J. Crowder 1.1m200 gold badges2k silver badges1.9k bronze badges asked Jun 15, 2012 at 11:27 Shahid GhafoorShahid Ghafoor 3,10318 gold badges73 silver badges125 bronze badges 2
  • 2 This isn't a jQuery thing, it's a JavaScript thing. I've added the tag for you. – T.J. Crowder Commented Jun 15, 2012 at 11:29
  • No offense but this looks like "give me the codes" type of a question. You should consider telling us what you tried first. – Liviu T. Commented Jun 15, 2012 at 13:34
Add a ment  | 

4 Answers 4

Reset to default 6

You can validate the string via a regular expression and String#match:

if (this.value.match(/^-?\d+(?:\.\d){0,1}$/)) {
    // It's valid
}

Or more jQuery-ish (and the above doesn't support textarea reliably, just input):

if ($(this).val().match(/^-?\d+(?:\.\d){0,1}$/)) {
    // It's valid
}

(E.g., this.value => $(this).val().)

Breaking the regex down:

  • ^ - Match start of string
  • -? - A single optional - character
  • \d+ - One or more digits (0-9)
  • (?:...) - A non-capturing grouping, containing:
    • \.\d - At most one . followed by a single digit
  • {0,1} - Allow the non-capturing grouping zero or one time
  • $ - Match end of string

Note that the above rejects -.1. If you want to accept it, it gets more plex, but the link above should help.

Gratuitous live example | source

Try this piece of code.

$('[name="pm"]').keyup(function() {
   if($(this).val().indexOf('-') != 0){ 
      var val = $(this).val();
      $(this).val("-" + val);
   }
});

In case it does not work, replace this with $('[name="pm"]')

Arrangement and addition for specified solution:

From @Some_Coder Answer

1) First Do this

http://www.texotela.co.uk/code/jquery/numeric/

from playmaker answer with modification

$('[name="pm"]').keyup(function() {

   if($(this).val().indexOf('-') != 0){ 
      var val = $(this).val();
      $(this).val("-" + val);
   }


if ($(this).val() == '-') {
            $(this).val('');
        }
});

You will get the desire result !

if you use jQuery, than you can use this plugin.

http://www.texotela.co.uk/code/jquery/numeric/

本文标签: javascriptvalidate negative number in jquery with one decimal placeStack Overflow