HTML input do not allow numbers

2019-06-07 09:20发布

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?

标签: html5 input
4条回答
唯我独甜
2楼-- · 2019-06-07 09:41

You have several options....

Regardless of the options, you will be using regular expressions in some way shape or form.

You can do it on the client side using JavaScript...

function Validate () {

  var inputValue = document.getElementById("test").value;
  var reg = new RegExp('^\\d+$');
  var test = reg.test(inputValue);
  
  //--Do something with test--
  console.log(test);
  
}
<input id="test" class="form-control" type="text" />
<button onClick="Validate()">Validate</button>

If it is just plain HTML with no server side code you will need to use JavaScript.

EDIT

And as far as I know this is supported in all browsers that support JavaScript regardless of version.

查看更多
聊天终结者
3楼-- · 2019-06-07 09:45

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.

查看更多
Fickle 薄情
4楼-- · 2019-06-07 09:47

no input alows just text:

http://www.w3schools.com/html/html_form_input_types.asp

... you can try js + action on input like onkeydown

http://www.w3schools.com/jsref/event_onkeydown.asp

and validate by regEx (just letters)

Regex to match only letters

can better control what happens when good or bad validation. Only the alert or change color etc.

查看更多
ゆ 、 Hurt°
5楼-- · 2019-06-07 09:56

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>

查看更多
登录 后发表回答