Shahid Ghafoor
Shahid Ghafoor

Reputation: 3103

validate negative number in jquery with one decimal place

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() {

    //?

 });

Upvotes: 0

Views: 5899

Answers (4)

Both FM
Both FM

Reputation: 770

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 !

Upvotes: 1

Playmaker
Playmaker

Reputation: 1456

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"]')

Upvotes: 1

some_coder
some_coder

Reputation: 340

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

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

Upvotes: 0

T.J. Crowder
T.J. Crowder

Reputation: 1074475

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 complex, but the link above should help.

Gratuitous live example | source

Upvotes: 6

Related Questions