Numeric input field JavaScript custom validation2019 Community Moderator ElectionValidate decimal numbers in JavaScript - IsNumeric()How to validate an email address in JavaScript?How do JavaScript closures work?How to validate an email address using a regular expression?Which equals operator (== vs ===) should be used in JavaScript comparisons?How do I include a JavaScript file in another JavaScript file?How to replace all occurrences of a string in JavaScriptWhat does “use strict” do in JavaScript, and what is the reasoning behind it?How to check whether a string contains a substring in JavaScript?How do I remove a particular element from an array in JavaScript?

Should a narrator ever describe things based on a characters view instead of fact?

UK Tourist Visa- Enquiry

Should I be concerned about student access to a test bank?

Did Nintendo change its mind about 68000 SNES?

Which partition to make active?

Do I need an EFI partition for each 18.04 ubuntu I have on my HD?

Why is this tree refusing to shed its dead leaves?

Is this Pascal's Matrix?

Emojional cryptic crossword

Can other pieces capture a threatening piece and prevent a checkmate?

What will the Frenchman say?

PTIJ: Why do we make a Lulav holder?

Why is indicated airspeed rather than ground speed used during the takeoff roll?

Exposing a company lying about themselves in a tightly knit industry: Is my career at risk on the long run?

Have any astronauts/cosmonauts died in space?

How are passwords stolen from companies if they only store hashes?

How to find the largest number(s) in a list of elements, possibly non-unique?

Pre-Employment Background Check With Consent For Future Checks

Turning a hard to access nut?

What are the rules for concealing thieves' tools (or items in general)?

Is VPN a layer 3 concept?

Why I don't get the wanted width of tcbox?

What is the difference between something being completely legal and being completely decriminalized?

What is the tangent at a sharp point on a curve?



Numeric input field JavaScript custom validation



2019 Community Moderator ElectionValidate decimal numbers in JavaScript - IsNumeric()How to validate an email address in JavaScript?How do JavaScript closures work?How to validate an email address using a regular expression?Which equals operator (== vs ===) should be used in JavaScript comparisons?How do I include a JavaScript file in another JavaScript file?How to replace all occurrences of a string in JavaScriptWhat does “use strict” do in JavaScript, and what is the reasoning behind it?How to check whether a string contains a substring in JavaScript?How do I remove a particular element from an array in JavaScript?










0















I have an input numeric field where I registered all changed events:



  • onchange

  • onkeydown

  • onkeyup

  • onmousedown

  • onmouseup

I need to permit inserting only numeric values with these rules:



  • Values between 0 and 24

  • It is possible to have decimal values.

  • Decimal value must be have only 1 decimal digit.

  • Decimal section must be a multiple of 0.5.

I need to immediately replace the old value if the current value is invalid.



So I have to accept, for example, values like these:



  • 0

  • 0.5

  • 12

  • 23.5

  • 24

I can't accept values like these:



  • Hello

  • -0,

  • -1

  • .

  • ,,

  • .5

  • 25

  • --2

  • ...

  • e

I tried to use this code, but it does not cover all cases:



function customValidation(value) (parseFloat(value) <= 24 && parseFloat(value) >= 0));


function eventListner(el)
if (customValidation(el.value))
el.oldValue = el.value;
else if (el.hasOwnProperty("oldValue"))
el.value = el.oldValue;











share|improve this question
























  • So in your RegEx you need to match 1 or more digits followed by an optional decimal symbol and 5?

    – PM 77-1
    Mar 6 at 23:48















0















I have an input numeric field where I registered all changed events:



  • onchange

  • onkeydown

  • onkeyup

  • onmousedown

  • onmouseup

I need to permit inserting only numeric values with these rules:



  • Values between 0 and 24

  • It is possible to have decimal values.

  • Decimal value must be have only 1 decimal digit.

  • Decimal section must be a multiple of 0.5.

I need to immediately replace the old value if the current value is invalid.



So I have to accept, for example, values like these:



  • 0

  • 0.5

  • 12

  • 23.5

  • 24

I can't accept values like these:



  • Hello

  • -0,

  • -1

  • .

  • ,,

  • .5

  • 25

  • --2

  • ...

  • e

I tried to use this code, but it does not cover all cases:



function customValidation(value) (parseFloat(value) <= 24 && parseFloat(value) >= 0));


function eventListner(el)
if (customValidation(el.value))
el.oldValue = el.value;
else if (el.hasOwnProperty("oldValue"))
el.value = el.oldValue;











share|improve this question
























  • So in your RegEx you need to match 1 or more digits followed by an optional decimal symbol and 5?

    – PM 77-1
    Mar 6 at 23:48













0












0








0








I have an input numeric field where I registered all changed events:



  • onchange

  • onkeydown

  • onkeyup

  • onmousedown

  • onmouseup

I need to permit inserting only numeric values with these rules:



  • Values between 0 and 24

  • It is possible to have decimal values.

  • Decimal value must be have only 1 decimal digit.

  • Decimal section must be a multiple of 0.5.

I need to immediately replace the old value if the current value is invalid.



So I have to accept, for example, values like these:



  • 0

  • 0.5

  • 12

  • 23.5

  • 24

I can't accept values like these:



  • Hello

  • -0,

  • -1

  • .

  • ,,

  • .5

  • 25

  • --2

  • ...

  • e

I tried to use this code, but it does not cover all cases:



function customValidation(value) (parseFloat(value) <= 24 && parseFloat(value) >= 0));


function eventListner(el)
if (customValidation(el.value))
el.oldValue = el.value;
else if (el.hasOwnProperty("oldValue"))
el.value = el.oldValue;











share|improve this question
















I have an input numeric field where I registered all changed events:



  • onchange

  • onkeydown

  • onkeyup

  • onmousedown

  • onmouseup

I need to permit inserting only numeric values with these rules:



  • Values between 0 and 24

  • It is possible to have decimal values.

  • Decimal value must be have only 1 decimal digit.

  • Decimal section must be a multiple of 0.5.

I need to immediately replace the old value if the current value is invalid.



So I have to accept, for example, values like these:



  • 0

  • 0.5

  • 12

  • 23.5

  • 24

I can't accept values like these:



  • Hello

  • -0,

  • -1

  • .

  • ,,

  • .5

  • 25

  • --2

  • ...

  • e

I tried to use this code, but it does not cover all cases:



function customValidation(value) (parseFloat(value) <= 24 && parseFloat(value) >= 0));


function eventListner(el)
if (customValidation(el.value))
el.oldValue = el.value;
else if (el.hasOwnProperty("oldValue"))
el.value = el.oldValue;








javascript html regex validation






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Mar 7 at 2:41









karel

2,22352732




2,22352732










asked Mar 6 at 23:37









SafariSafari

4,0581462130




4,0581462130












  • So in your RegEx you need to match 1 or more digits followed by an optional decimal symbol and 5?

    – PM 77-1
    Mar 6 at 23:48

















  • So in your RegEx you need to match 1 or more digits followed by an optional decimal symbol and 5?

    – PM 77-1
    Mar 6 at 23:48
















So in your RegEx you need to match 1 or more digits followed by an optional decimal symbol and 5?

– PM 77-1
Mar 6 at 23:48





So in your RegEx you need to match 1 or more digits followed by an optional decimal symbol and 5?

– PM 77-1
Mar 6 at 23:48












2 Answers
2






active

oldest

votes


















0














Sounds like you could benefit from using a "number" input type and just specifying the min, max, and step properties instead of using a RegEx for validity. For example:



<input type="number" name="myNumber" id="myNumber" min="0" max="24" step="0.5">


Then you can just check the validity with the standard methods available:



let myNumberInput = document.getElementById("myNumber");
let myNumberIsValid = myNumberInput.checkValidity();


The MDN web docs also has some useful information on their Constraint validation API page.






share|improve this answer






























    0














    This regex covers all cases:



    /^(?:(?:d|1d|2[0-3])(?:.[05])?|24(?:.0)?)$/


    https://regex101.com/r/KZeVKa/1



    Expanded:



     ^ # BOS
    (?:
    (?: # 0 - 23.5
    d
    | 1 d
    | 2 [0-3]
    )
    (?: . [05] )?
    | # or,
    24 # 24.0
    (?: . 0 )?
    )
    $ # EOS





    share|improve this answer






















      Your Answer






      StackExchange.ifUsing("editor", function ()
      StackExchange.using("externalEditor", function ()
      StackExchange.using("snippets", function ()
      StackExchange.snippets.init();
      );
      );
      , "code-snippets");

      StackExchange.ready(function()
      var channelOptions =
      tags: "".split(" "),
      id: "1"
      ;
      initTagRenderer("".split(" "), "".split(" "), channelOptions);

      StackExchange.using("externalEditor", function()
      // Have to fire editor after snippets, if snippets enabled
      if (StackExchange.settings.snippets.snippetsEnabled)
      StackExchange.using("snippets", function()
      createEditor();
      );

      else
      createEditor();

      );

      function createEditor()
      StackExchange.prepareEditor(
      heartbeatType: 'answer',
      autoActivateHeartbeat: false,
      convertImagesToLinks: true,
      noModals: true,
      showLowRepImageUploadWarning: true,
      reputationToPostImages: 10,
      bindNavPrevention: true,
      postfix: "",
      imageUploader:
      brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
      contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
      allowUrls: true
      ,
      onDemand: true,
      discardSelector: ".discard-answer"
      ,immediatelyShowMarkdownHelp:true
      );



      );













      draft saved

      draft discarded


















      StackExchange.ready(
      function ()
      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55033881%2fnumeric-input-field-javascript-custom-validation%23new-answer', 'question_page');

      );

      Post as a guest















      Required, but never shown

























      2 Answers
      2






      active

      oldest

      votes








      2 Answers
      2






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes









      0














      Sounds like you could benefit from using a "number" input type and just specifying the min, max, and step properties instead of using a RegEx for validity. For example:



      <input type="number" name="myNumber" id="myNumber" min="0" max="24" step="0.5">


      Then you can just check the validity with the standard methods available:



      let myNumberInput = document.getElementById("myNumber");
      let myNumberIsValid = myNumberInput.checkValidity();


      The MDN web docs also has some useful information on their Constraint validation API page.






      share|improve this answer



























        0














        Sounds like you could benefit from using a "number" input type and just specifying the min, max, and step properties instead of using a RegEx for validity. For example:



        <input type="number" name="myNumber" id="myNumber" min="0" max="24" step="0.5">


        Then you can just check the validity with the standard methods available:



        let myNumberInput = document.getElementById("myNumber");
        let myNumberIsValid = myNumberInput.checkValidity();


        The MDN web docs also has some useful information on their Constraint validation API page.






        share|improve this answer

























          0












          0








          0







          Sounds like you could benefit from using a "number" input type and just specifying the min, max, and step properties instead of using a RegEx for validity. For example:



          <input type="number" name="myNumber" id="myNumber" min="0" max="24" step="0.5">


          Then you can just check the validity with the standard methods available:



          let myNumberInput = document.getElementById("myNumber");
          let myNumberIsValid = myNumberInput.checkValidity();


          The MDN web docs also has some useful information on their Constraint validation API page.






          share|improve this answer













          Sounds like you could benefit from using a "number" input type and just specifying the min, max, and step properties instead of using a RegEx for validity. For example:



          <input type="number" name="myNumber" id="myNumber" min="0" max="24" step="0.5">


          Then you can just check the validity with the standard methods available:



          let myNumberInput = document.getElementById("myNumber");
          let myNumberIsValid = myNumberInput.checkValidity();


          The MDN web docs also has some useful information on their Constraint validation API page.







          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Mar 7 at 0:01









          musicinmyheadmusicinmyhead

          1,27979




          1,27979























              0














              This regex covers all cases:



              /^(?:(?:d|1d|2[0-3])(?:.[05])?|24(?:.0)?)$/


              https://regex101.com/r/KZeVKa/1



              Expanded:



               ^ # BOS
              (?:
              (?: # 0 - 23.5
              d
              | 1 d
              | 2 [0-3]
              )
              (?: . [05] )?
              | # or,
              24 # 24.0
              (?: . 0 )?
              )
              $ # EOS





              share|improve this answer



























                0














                This regex covers all cases:



                /^(?:(?:d|1d|2[0-3])(?:.[05])?|24(?:.0)?)$/


                https://regex101.com/r/KZeVKa/1



                Expanded:



                 ^ # BOS
                (?:
                (?: # 0 - 23.5
                d
                | 1 d
                | 2 [0-3]
                )
                (?: . [05] )?
                | # or,
                24 # 24.0
                (?: . 0 )?
                )
                $ # EOS





                share|improve this answer

























                  0












                  0








                  0







                  This regex covers all cases:



                  /^(?:(?:d|1d|2[0-3])(?:.[05])?|24(?:.0)?)$/


                  https://regex101.com/r/KZeVKa/1



                  Expanded:



                   ^ # BOS
                  (?:
                  (?: # 0 - 23.5
                  d
                  | 1 d
                  | 2 [0-3]
                  )
                  (?: . [05] )?
                  | # or,
                  24 # 24.0
                  (?: . 0 )?
                  )
                  $ # EOS





                  share|improve this answer













                  This regex covers all cases:



                  /^(?:(?:d|1d|2[0-3])(?:.[05])?|24(?:.0)?)$/


                  https://regex101.com/r/KZeVKa/1



                  Expanded:



                   ^ # BOS
                  (?:
                  (?: # 0 - 23.5
                  d
                  | 1 d
                  | 2 [0-3]
                  )
                  (?: . [05] )?
                  | # or,
                  24 # 24.0
                  (?: . 0 )?
                  )
                  $ # EOS






                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Mar 7 at 0:52









                  slnsln

                  26.7k31638




                  26.7k31638



























                      draft saved

                      draft discarded
















































                      Thanks for contributing an answer to Stack Overflow!


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid


                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.

                      To learn more, see our tips on writing great answers.




                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function ()
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55033881%2fnumeric-input-field-javascript-custom-validation%23new-answer', 'question_page');

                      );

                      Post as a guest















                      Required, but never shown





















































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown

































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown







                      Popular posts from this blog

                      Save data to MySQL database using ExtJS and PHP [closed]2019 Community Moderator ElectionHow can I prevent SQL injection in PHP?Which MySQL data type to use for storing boolean valuesPHP: Delete an element from an arrayHow do I connect to a MySQL Database in Python?Should I use the datetime or timestamp data type in MySQL?How to get a list of MySQL user accountsHow Do You Parse and Process HTML/XML in PHP?Reference — What does this symbol mean in PHP?How does PHP 'foreach' actually work?Why shouldn't I use mysql_* functions in PHP?

                      Compiling GNU Global with universal-ctags support Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 23, 2019 at 23:30 UTC (7:30pm US/Eastern) Data science time! April 2019 and salary with experience The Ask Question Wizard is Live!Tags for Emacs: Relationship between etags, ebrowse, cscope, GNU Global and exuberant ctagsVim and Ctags tips and trickscscope or ctags why choose one over the other?scons and ctagsctags cannot open option file “.ctags”Adding tag scopes in universal-ctagsShould I use Universal-ctags?Universal ctags on WindowsHow do I install GNU Global with universal ctags support using Homebrew?Universal ctags with emacsHow to highlight ctags generated by Universal Ctags in Vim?

                      Add ONERROR event to image from jsp tldHow to add an image to a JPanel?Saving image from PHP URLHTML img scalingCheck if an image is loaded (no errors) with jQueryHow to force an <img> to take up width, even if the image is not loadedHow do I populate hidden form field with a value set in Spring ControllerStyling Raw elements Generated from JSP tagds with Jquery MobileLimit resizing of images with explicitly set width and height attributeserror TLD use in a jsp fileJsp tld files cannot be resolved