Search code examples
javascripthtmlcssoracle-apex-5

how to restrict number field to enter only numbers in oracle apex


I'm new to oracle apex. Currently I'm working on oracle apex 5.0. I've created an item of type number field. I want this field for entering mobile number. So, I used format masking like '9999999999'.
Now problem is, after executing that application I can able to enter alphabets also. For now, I made a validation on it, but I want my item to accept only number as input. User can't be able to add any alphabets in it.
I've also tried, putting input type="tel" maxlength="10" and input type="number" max="10" this code in my HTML Form Element Attributes field as well as HTML Form Element CSS Classes field but it doesn't work.

No matter which query I put in HTML Form Element Attributes it will result in problem which is shown in image Problem with HTML Form Element Attributes.Now, as you can see in that image, this time I've added <input type="tel" maxlength=10 pattern="[0-9]{3}-[0-9]{3}-[0-9]{4}"> this statement, but having that same problem.
Now I also tried to put that statement into HTML Form Element CSS Classes, and here that problem is not appearing but still I'm able to add alphabets in it.

Please guide me how to do that.


Solution

  • Use JavaScript to listen onkeydown event and check the keycode.

    If the keycode is a letter prevent it from being inserted into the input element. To see the list of keycodes check here

    function validateNumber(event) {
      var keyCode = event.keyCode;
      var excludedKeys = [8, 37, 39, 46];
    
      if (!((keyCode >= 48 && keyCode <= 57) ||
          (keyCode >= 96 && keyCode <= 105) ||
          (excludedKeys.includes(keyCode)))) {
        console.log("alphabets are not allowed");
        event.preventDefault();
    
      }
    
      console.log("keycode: " + keyCode);
    }
    <form>
    
      <div>
        <label>Mobile Number</label>
        <input type="tel" placeholder="Enter Mobile no" onkeydown="return validateNumber(event)" required>
      </div>
    
    
    </form>

    Working fiddle