Home > Enterprise >  How to validate input field with numbers only using javascript?
How to validate input field with numbers only using javascript?

Time:11-13

I am new to Javascript, I need to validate the input field. I wish to enter only numbers, not allowing alphabets or special characters. I need to show the error message below the input field. Validation rules for the input field are:

  • Should be numbers only
  • Numbers should be greater than 1 and less than available quantity. I have form with three input fields, available quantity, quantity and bid price. Validation on value entered on quantity field should be greater than 1 and less than the available quantity is working fine. But I need to enter only numbers using javascript.

What I have tried is

<form method="post" action="/truckianBidSave/{{id}}" id="reviewForm">
                                    <input type="hidden" name="_token" value="{{csrf_token()}}" />
                                     <input type="hidden" name="user_name" value="{{auth_user().first_name}}" />
                                  <!--  <div class="form-group row">
                                        <label class="col-sm-4 col-form-label">Select Milege Gap: </label>
                                        <div class="col-sm-8">
                                        <select class="form-select" name="mileage" id="mileage" onchange="getOption()">
                                            <option>Select </option>
                                            {% for p in product_data %}
                                            <option value="{{p.number_of_products}},{{p.number_of_products_sold}},{{p.mileage_gap}}">{{p.mileage_gap}}</option>
                                            {% endfor %}
                                        </select>
                                        </div>
                                    </div>-->
                                    <div class="form-group row">
                                        {% set total=0 %}
                                        {% set sold=0 %}
                                         {% for p in product_data %}
                                        {% set total =total p.number_of_products %}
                                        {% set sold=sold p.number_of_products_sold %}
                                        {% endfor %}
                                        {% set available=total-sold %}
                                        <label for="available" class="col-sm-4 col-form-label">Available Quantity: </label>
                                        <div class="col-sm-8">
                                            <input type="text" class="form-control" id="available" readonly name="available_qty" value={{available}} />
                                        </div>
                                    </div>
                                   
                                    <div class="form-group row">
                                        <label for="qty"  class="col-sm-4 col-form-label"> Quantity: </label>
                                        <div class="col-sm-8">
                                            <input type="text" id="qty" name="qty"  class="form-control"     oninput="checkInput(this);"   required />
                                            <p id="qty-msg">
                                            </p>
                                        </div>
                                    </div>
                                    
                                    <div class="form-group row">
                                        <label for="inputBid"  class="col-sm-4 col-form-label">Enter Bid Price</label>
                                        <div class="col-sm-8">
                                            <input type="text" class="form-control" id="inputBid" name="bid" oninput="this.value = this.value.replace(/[^0-9.]/g, '').replace(/(\..*)\./g, '$1');"/>
                                        </div>
                                    </div>
                                    <div class="form-group text-center">
                                        <input type="submit" class="btn btn-primary" id="btn" name="send" value="Send" disabled="disabled">
                                    </div>
                                </form>

Javascript code:

function checkInput(item)
    {var available=document.getElementById("available");
        var msg=document.getElementById("qty-msg");
       if(parseInt(item.value)>parseInt(available.value) )
            { 
                
                item.value='';
                msg.innerHTML="* Value must be less than Availabe quantity " available.value ;
                msg.style.color="red"; 
            }
        else if(parseInt(item.value)<1)
            {
                item.value='';
                msg.innerHTML="* Value must be greater than 1" ;
                msg.style.color="red"; 
            }
        else if('/^[A-Za-z] $/'.test(item.value))
            {   alert('hi');
                item.value='';
                msg.innerHTML="* Only numbers allowed" ;
                msg.style.color="red"; 
            }

How to not allow alphabets and special characters in input filed using javascript.

CodePudding user response:

Use this instead of your pattern

!(/^[0-9]{1,}$/.test(item.value))

It'll return true if the value contains a string, otherwise, it'll return false.

CodePudding user response:

You may use <input type="number"> for the 'qty' input. See https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/number for details.

A javascript filter like

document.getElementById('qty').addEventListener('keydown',
  function(event){
    if(!event.key.match(/^[0-9]$/)){
      event.preventDefault();
    }
 }
);

is never perfectly safe, i.e., it will not work on some old browsers or mobile browsers.

  • Related