Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 3 of 3
  1. #1
    New Coder
    Join Date
    Aug 2002
    Location
    Malaysia
    Posts
    62
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Forcing only numbers with .0 or .5 only

    Dear all, is there any reference to this javascript that forces a user to enter a number that is either a whole number or only with a .5 decimal? e.g. 1, 2, 3.5, 8.5, 9.0 etc. If the user enters say 8.4, 9.3, 7.7, an error message will appear and clears the current textbox?

  • #2
    Supreme Master coder! Philip M's Avatar
    Join Date
    Jun 2002
    Location
    London, England
    Posts
    18,079
    Thanks
    203
    Thanked 2,542 Times in 2,520 Posts
    if (/\.[12346789]/g.test(thetextbox.value)) {
    alert ("Error");
    thetextbox.value="";
    thetextbox.focus
    }
    else {

    ...... OK
    }

    European users my place a comma , as seperator so better

    if (/(\.|\,)[12346789]/g.test(thetextbox.value)) {

    Some people, when confronted with a problem, think "I know, I'll use regular expressions." Now they have two problems." — Jamie Zawinski.

  • #3
    Supreme Master coder! Philip M's Avatar
    Join Date
    Jun 2002
    Location
    London, England
    Posts
    18,079
    Thanks
    203
    Thanked 2,542 Times in 2,520 Posts
    In fact on second thoughts this has an imperfection. It will block 6.8 for example but not 6.08.

    Another approach is simply using modulo arithmetic:

    x = thetextbox.value
    if ((x%0.5) !=0 ) {
    alert ("Error!");
    thetextbox.value="";
    thetextbox.focus;
    }


  •  

    Posting Permissions

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