SitePoint Sponsor

User Tag List

Results 1 to 3 of 3

Hybrid View

  1. #1
    SitePoint Member
    Join Date
    Aug 2011
    Posts
    2
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    How can I use Javascript to enforce a 0.0 numeric format?

    Hello,

    I need to limit input in form field to be greater than 0 and less than one. As such, it can be either the integer 1 or a floating point. The business requirement calls for a format of 0.0

    I'm new to actually 'writing' javascript and I'm not having much luck.

    Any help would be appreciated.

    I tried some regular expressions with an onkeypress event and I also tried just directly validating based on charcode and I thought I had it figured out and then I realized that I was able to type more than one period '.' and now I find myself here (many hours later).

    There has got to me a easier way to do this. Some sort of mask function or such?

    If there is a JavaScript library that has a good mask function that I could use for this, that would work as well.

    Best regards,
    Kevin

  2. #2
    SitePoint Guru
    Join Date
    Apr 2006
    Posts
    802
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Simpler to use numbers than regular expressions, and then convert the valid number to the string format you want.

    Code:
    function zeroToOne(field){
    	var n= Number(field.value) || 0;
    	return Math.max(0, (Math.min(1, n))).toFixed(1)
    }
    //test with dummy input

    var inputfield={value: '.2'};

    alert(zeroToOne(inputfield));

  3. #3
    SitePoint Member
    Join Date
    Aug 2011
    Posts
    2
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Thanks, I will give it a try and see how it goes.

    KR


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •