skip to Main Content

I would like to validate a price field in html form that a leading ZERO like 0350, 024879, etc. are not allowed and jQuery will issue a warning while typing. Here is jQuery should do when typing a leading ZERO number into the price field:

a) a popup warning message like ‘ZERO leading number not allowed. Please correct it!’

b) Clear off or remove that invalid price from the price field with/without a delay

c) What is the correct Regex for validating just ZERO leading numeric string? for example, typing 09, 038, etc. is not accepted. But typing 0u, 0& (with non numeric characters) is accepted.

Here is my codes:

HTML:

    <input type="text" id="price" name="price"> 

jQuery:

    jQuery('#price').on("keyup", function() {
      var price = $(this).val();
      var partern = /^(?:[1-9][0-9]*|0)$/;
      var valid = partern.test(price);

      if (!valid) {
        alert('Invalid price. Please input numerical characters');
        setTimeout(function (e) {
            $this.val(null);
        },500);
      }
    });

Any advice would be very appreciated.

2

Answers


  1. Chosen as BEST ANSWER

    FIXED: Here is my codes:

        HTML:
        <input type="text" id="price" name="price"> 
    
        jQuery:
        jQuery('#price').on("keyup", function() {
          var price = $(this).val();
          var partern = /^(?:[1-9][0-9]*|0)$/;
          var valid = partern.test(price);
    
          if (!valid) {
            alert('Invalid price. Please input numerical characters');
           // setTimeout(function (e) {
                ($this).val(null);    // does not work with setTimeout()
           // },500);
          }
        });
        
        
    

    Many thanks.


  2. ANOTHER FIXED:
    I have issue with using both this or (this) in jQuery on my WordPress; they dont work with setTimeout(), and cannot generalise this issue for other Wordpres theme. But I tested this one:

        setTimeout(function (e) {
        //  $this.val(null);      // $this works with setTimeout inside another setTimeout
          jQuery('#price').val('');   // Reset or clear off url input field after a warning
        },500);
        
    

    jQuery(‘#price’).val(”); does work with setTimeout() function. Here are full codes with a time delay:

        HTML:
        <input type="text" id="price" name="price"> 
    
        jQuery:
        jQuery('#price').on("keyup", function() {
          var price = $(this).val();
          var partern = /^(?:[1-9][0-9]*|0)$/;
          var valid = partern.test(price);
    
          if (!valid) {
            alert('Invalid price. Please input numerical characters');
            setTimeout(function (e) {
                jQuery('#price').val('');    // does not work with setTimeout()
            },500);
          }
        });
    

    Many thanks

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search