How to modify this script to allow negative numbers??

Discussion in 'Javascript' started by tlyczko, Nov 27, 2005.

  1. tlyczko

    tlyczko Guest

    Hello Rob B posted this wonderful code in another thread,

    http://groups.google.com/group/comp...538025980dd/6ead9d5e61be85f0#6ead9d5e61be85f0

    I could not figure out how to reply to the thread per se using Google
    Groups and so please forgive me for cutting and pasting (I emailed him
    but he may not have time to check his email), and I am hoping someone
    might be able to tell me how I can change this script to allow negative
    numbers.

    My question is:

    How can I modify it to allow a minus sign to allow negative numbers??

    I want to use it in a purchase requisition form where sometimes
    negative numbers are necessary.

    Ideally I want to allow a negative number typed in, then when it goes
    to be printed I would want to reformat it (either with JS or CSS) so it
    has ( ) to show it is
    a negative/credit type of number for Accounts Payable to act
    accordingly.

    Thank you, Tom

    The Chameleon Lives! :)
    Your welcome, Rogue.

    <?xml version="1.0" encoding="iso-8859-1"?>
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
    <head>
    <title>untitled</title>
    <script type="text/javascript">
    //<![CDATA[

    cF.RE1 = /^\d*\.?\d*$/;
    cF.RE2 = /\.\d{3,}$/;
    cF.RE3 = /\.(?=[^.]*\.)/g;
    cF.RE4 = /[^\d.]/g;
    cF.RE5 = /\.(?=[^.]*\.)/g;
    cF.RE6 = /^(\d*\.\d{2}).+$/;
    cF.RE7 = /(\.\d{0,1})$/;
    cF.RE8 = /^([^.]+)$/;

    String.prototype.reverse = function()
    {
    return this.split('').reverse().join('');

    }

    function cF(fld, onblur)
    {
    var v = fld.value;
    if (!cF.RE1.test(v) || cF.RE2.test(v))
    {
    var ltdot = (fld.dotpos == v.indexOf('.') ?
    v.lastIndexOf('.') < fld.dotpos :
    v.indexOf('.') < fld.dotpos);
    if (ltdot)
    v = v.reverse();
    v = v.replace(cF.RE3,'');
    if (ltdot)
    v = v.reverse();
    v = v.replace(cF.RE4,'').
    replace(cF.RE5,'').
    replace(cF.RE6,'$1');
    fld.value = v;
    }
    fld.dotpos = v.indexOf('.');
    if (onblur)
    fld.value = v.replace(cF.RE7, '$10').
    replace(cF.RE7, '$10').
    replace(cF.RE8, '$1.00');

    }

    //]]>
    </script>
    </head>
    <body style="font:100% arial;margin:300px;"
    onload="f=document.forms[0];f.reset();f.foo.focus()">
    <form onreset="foo.focus()">
    $ <input type="text" name="foo" value="" size="10" maxlength="8"
    style="font:75% arial;text-align:center;border:1px black solid;"
    onkeyup="return cF(this,false)"
    onblur="return cF(this,true)" />
    <input type="reset" value="clear" style="font:75% arial;border:1px
    black
    solid;" />
    </form>
    </body>
    </html>

    *** Sent via Developersdex http://www.developersdex.com ***
    Don't just participate in USENET...get rewarded for it!
    tlyczko, Nov 27, 2005
    #1
    1. Advertising

  2. tlyczko

    RobG Guest

    tlyczko wrote:
    > Hello Rob B posted this wonderful code in another thread,
    >
    > http://groups.google.com/group/comp...538025980dd/6ead9d5e61be85f0#6ead9d5e61be85f0
    >
    > I could not figure out how to reply to the thread per se using Google
    > Groups and so please forgive me for cutting and pasting (I emailed him
    > but he may not have time to check his email), and I am hoping someone
    > might be able to tell me how I can change this script to allow negative
    > numbers.


    There's probably not much point in replying to a thread that is 12
    months old.

    >
    > My question is:
    >
    > How can I modify it to allow a minus sign to allow negative numbers??
    >


    Very probably, but the script itself is very much more complex than need
    be. What are you trying to do? If you want to restrict user input to 5
    digits, one decimal point and two more digits, then use a regular
    expression, there are many here that can be modified for your purpose:

    <URL: http://www.merlyn.demon.co.uk/js-valid.htm#VNP >


    The one you want is:

    /^[-]?\d{0,5}(\.\d{0,2})?$/

    I loath scripts that modify what I am typing as I type it. It is much
    better to show a message adjacent to the input box to remind the user
    that the format is not what you want and allow them to modify it. Many
    users will simply type the extra digits anyway and likely not notice
    that you've removed them. And if they have JavaScript disabled, your
    script will not do anything.

    Don't use an alert (especially as this seems to be for an intranet where
    the users are likely experienced data input operators), that is even
    worse. An example is below.


    <script type="text/javascript">
    //<![CDATA[

    function testNum(num, erId){
    var er = document.getElementById(erId);
    var re = /^[-]?\d{0,5}(\.\d{0,2})?$/;
    if (num && !re.test(num) ) {
    er.innerHTML = 'Invalid number, required format is [-]nnnnn.nn';
    } else {
    er.innerHTML = '';
    }
    }

    //]]>
    </script>
    </head><body>
    <form action="">
    $ <input type="text" name="foo" value="" size="10" maxlength="9"
    onkeyup="testNum(this.value, 'msg');" />
    <input type="reset" value="clear" />
    </form>
    <div id="msg"></div>
    </body>


    > I want to use it in a purchase requisition form where sometimes
    > negative numbers are necessary.


    The above is not production ready, it just gives you a start and an
    example of how to use a regular expression more efficiently.


    > Ideally I want to allow a negative number typed in, then when it goes
    > to be printed I would want to reformat it (either with JS or CSS) so it
    > has ( ) to show it is
    > a negative/credit type of number for Accounts Payable to act
    > accordingly.


    Then use onblur to add the parenthesis. But you have limited the number
    of characters in the input box, so how will you add the extra two
    characters? If you modify the input's 'length' parameter, then the user
    can go back, remove the brackets and add more numbers - so you have some
    UI issues to deal with. Your original doesn't allow room for the minus
    sign (unless you wanted 4 digits before the decimal).

    Or do you write the value to somewhere else in the page?

    [...]



    --
    Rob
    RobG, Nov 28, 2005
    #2
    1. Advertising

  3. tlyczko

    tlyczko Guest

    Thank you for your help!!

    I am RE-learning Javascript as I go. You were right, it was a
    1-year-old thread, I gambled and hopefully we have something here
    others can learn from.

    Merlyn's Javascript pages are wonderful but I find them sometimes
    rather abstract, because he uses a lot of includes to present things on
    his site and sometimes the demos etc. require the include files, so it
    can be a little difficult figuring out what to use.

    Thank you for the specific link, though. I missed it completely when I
    was reading his site before I found this script.

    A few hours after posting, I also found a great website,
    http://www.regexlib.com, which is a fantastic resource for regex
    patterns.

    I found one regex that although it is rather long, allows me to enter $
    and enclosing parentheses (and even commas), which are necessary for
    credits (to be subtracted) rather than debits (which will be added).
    Purchase requisitions rarely have credits, usually everything is added
    up.

    The link for the regex is
    http://www.regexlib.com/REDetails.aspx?regexp_id=625

    You asked a couple of questions: 1. Yes, I do some calculations with
    the numbers after they are entered; 2. Yes, I do need to modify the
    regex to allow $ and ( ), I can figure this out, as well as how to do
    the math for the totaling up, etc., I started this part already.

    Just two questions:

    1) Why did you use onkeyup?? I ask because I thought that one is
    supposed to use onchange for testing values or doing something with
    values, because I thought onkeyup catches every single keystroke, the
    user would never finish typing the number.

    2) What IS the best event for validating form field entries -- onblur,
    onchange, onkeyup (I am posting this to the group too).

    Thank you very much again.

    :) tom
    tlyczko, Nov 28, 2005
    #3
  4. RobG wrote:

    > <script type="text/javascript">
    > //<![CDATA[


    This is nonsense. Either you serve XHTML, then you should serve it as
    application/xhtml+xml and need the declaration for easily legible inline
    source code: user agents that support it, like Mozilla/5.0, will use their
    faster XML parser that only accepts well-formed documents; user agents that
    do not support it, like IE 6.x, will try to download it. Or you serve
    HTML, then serve it as text/html where the tagsoup parser will be used and
    CDATA declarations will have neither meaning nor will they be necessary
    as the `script' element's content is PCDATA by default _only_ in XHTML.

    The commented-out declaration was most certainly included in the attempt
    to serve XHTML as text/html to achieve what XHTML 1.0, Appendix C, calls
    "HTML compatibility". However, that section of the specification is
    flawed; it is trying to achieve what cannot be achieved (since HTML and
    XHTML are fundamentally different, especially in the meaning of the NET
    delimiter), and it is potentially harmful since it relies solely on
    afterwards non-specified error-correction by the user agent that, when
    applied, _contradicted_ the HTML standard in this regard.

    `<br />' in XHTML is `<br>&gt;' in HTML, _not_ `<br>', and CDATA content
    will end at the first `</' not at `]]>'.

    > [...]
    > //]]>
    > </script>


    <URL:http://hixie.ch/advocacy/xhtml>


    PointedEars
    Thomas 'PointedEars' Lahn, Nov 28, 2005
    #4
  5. tlyczko

    RobG Guest

    tlyczko wrote:
    > Thank you for your help!!
    >
    > I am RE-learning Javascript as I go. You were right, it was a
    > 1-year-old thread, I gambled and hopefully we have something here
    > others can learn from.
    >
    > Merlyn's Javascript pages are wonderful but I find them sometimes
    > rather abstract, because he uses a lot of includes to present things on
    > his site and sometimes the demos etc. require the include files, so it
    > can be a little difficult figuring out what to use.
    >
    > Thank you for the specific link, though. I missed it completely when I
    > was reading his site before I found this script.
    >
    > A few hours after posting, I also found a great website,
    > http://www.regexlib.com, which is a fantastic resource for regex
    > patterns.
    >
    > I found one regex that although it is rather long, allows me to enter $
    > and enclosing parentheses (and even commas), which are necessary for
    > credits (to be subtracted) rather than debits (which will be added).
    > Purchase requisitions rarely have credits, usually everything is added
    > up.
    >
    > The link for the regex is
    > http://www.regexlib.com/REDetails.aspx?regexp_id=625
    >
    > You asked a couple of questions: 1. Yes, I do some calculations with
    > the numbers after they are entered; 2. Yes, I do need to modify the
    > regex to allow $ and ( ), I can figure this out, as well as how to do
    > the math for the totaling up, etc., I started this part already.
    >
    > Just two questions:
    >
    > 1) Why did you use onkeyup?? I ask because I thought that one is
    > supposed to use onchange for testing values or doing something with
    > values, because I thought onkeyup catches every single keystroke, the
    > user would never finish typing the number.


    I used keyup because that is what you posted code. As this seems like
    an intranet application, you probably have users telling you what they
    want. onblur will only fire when the focus moves on.

    I just want you to be aware of the issues and can get your users to
    pick what they want - implement it however you want. Often developers
    force what they think should be done when the users have a much better
    idea of the required functionality.


    >
    > 2) What IS the best event for validating form field entries -- onblur,
    > onchange, onkeyup (I am posting this to the group too).


    Whatever your users like. If you use in-form error messages (like the
    one I posted as an example but maybe you want to format it better)
    then onkeyup is fine, just so long as the user's keystrokes aren't
    affected. They see the message and can decide whether to ignore it or
    not. Always keep the messages helpful and positive.

    Check again on submit as they may have missed a message. :)



    --
    Rob
    RobG, Nov 28, 2005
    #5
  6. tlyczko

    RobG Guest

    Thomas 'PointedEars' Lahn wrote:
    > RobG wrote:
    >
    >
    >><script type="text/javascript">
    >>//<![CDATA[

    >
    >
    > This is nonsense. Either you serve XHTML,


    Talk to the OP Thomas.


    [...]


    --
    Rob
    RobG, Nov 28, 2005
    #6
  7. tlyczko

    tlyczko Guest

    Thank you, Thomas, for the comments about CDATA, though there was no
    need to be so brusque.

    RobG correctly observed this is an intranet app. However, it's on IE
    6.x and someday later IE 7.x, so your "correct" way of serving the
    document won't work for IE 6.x. It will become an included *.js file
    anyway.

    RobG, thank you again for your helpful answers...I will probably use
    onchange as it is easier to understand initially, I have seen comments
    about problems with onblur, and I don't yet understand the difference
    between onchange and onblur, I need to read about this first.

    I will try onkeyup too and see what happens, and I will use a simpler
    regex / test mechanism than the code I posted at the beginning of this
    thread.

    Thank you again, everyone!!

    :) tom
    tlyczko, Nov 28, 2005
    #7
  8. tlyczko wrote:

    > Thank you, Thomas, for the comments about CDATA,
    > though there was no need to be so brusque.


    It was not the first time I explained it here.


    PointedEars
    Thomas 'PointedEars' Lahn, Nov 28, 2005
    #8
  9. tlyczko

    tlyczko Guest

    Hi RobG (and anyone else who may know),

    Thank you again for the sample code you provided above. For the most
    part it does what I need it to do.

    I tried out the sample code you gave me, it is very nice, onkeyup works
    adequately, but how do I make the error message go away after they have
    corrected the data input???

    Should I add an onchange or onblur event with much the same code for
    additional checking to see if the user has fixed the error???

    I definitely should have the error message go away after they have
    fixed it.

    Thank you,
    Tom
    tlyczko, Nov 28, 2005
    #9
  10. tlyczko

    tlyczko Guest

    tlyczko, Nov 28, 2005
    #10
  11. tlyczko

    tlyczko Guest

    I spoke too soon, the currency validator does allow adding parentheses
    if one types a negative number, try the examples.

    Thank you,
    :) tom
    tlyczko, Nov 28, 2005
    #11
  12. tlyczko

    tlyczko Guest

    I discovered that onkeypress fixes it for me, I just need to fix it so
    if only one digit or no digits after the decimal place it shows the
    error message, as well as allow minus signs.

    Thank you,
    :) tom
    tlyczko, Nov 28, 2005
    #12
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. prem_eda
    Replies:
    5
    Views:
    7,797
    Pieter Hulshoff
    Oct 11, 2004
  2. Jeff
    Replies:
    2
    Views:
    918
    clintonG
    Sep 19, 2006
  3. Andy B.
    Replies:
    0
    Views:
    272
    Andy B.
    Apr 28, 2010
  4. Ryan Taylor
    Replies:
    1
    Views:
    664
    Ryan Taylor
    Sep 9, 2004
  5. KathyB
    Replies:
    10
    Views:
    411
    Dr John Stockton
    Dec 24, 2003
Loading...

Share This Page