Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML input do not allow numbers

Tags:

html

input

Right now I have an input field like this:

<input class="form-control" type="text"/>

But it stills allows the input of numbers.

I want names to be input and want to display an error message when the string contains a number. How can I achieve this?

like image 758
b-m-f Avatar asked Apr 23 '15 12:04

b-m-f


People also ask

How do I restrict input to numbers in HTML?

To limit an HTML input box to accept numeric input, use the <input type="number">. With this, you will get a numeric input field. After limiting the input box to number, if a user enters text and press submit button, then the following can be seen “Please enter a number.”

How do I restrict the input field to accept only numbers?

You can use the <input> tag with attribute type='number'. This input field allows only numerical values. You can also specify the minimum value and maximum value that should be accepted by this field.


2 Answers

You can use native HTML5 field validation

like e-mail validation (fiddle): <input type="text" title="email" pattern="[^@]+@[^@]+\.[a-zA-Z]{2,6}" />

For your specific case you can use regexp like pattern="[a-zA-Z]*" (fiddle)

When you submit form it became highlighted with red border to show you validation error. In different browser it will behave slightly different.

I don't think there is standard way to override every default styling, however there are browser specific ways to do this (here).

For some style you can have css hooks in place for changes see here

Edit: updated fiddle.

like image 94
Mior Avatar answered Sep 30 '22 14:09

Mior


This should help you to type only characters:

$(function() {

  $('#txtNumeric').keydown(function (e) {
  
    if (e.shiftKey || e.ctrlKey || e.altKey) {
    
      e.preventDefault();
      
    } else {
    
      var key = e.keyCode;
      
      if (!((key == 8) || (key == 32) || (key == 46) || (key >= 35 && key <= 40) || (key >= 65 && key <= 90))) {
      
        e.preventDefault();
        
      }

    }
    
  });
  
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
  <b>Enter Text:</b>
  <input type="text" id="txtNumeric" />
</div>
like image 30
Ash Win Avatar answered Sep 30 '22 13:09

Ash Win