Javascript - validation, numbers only

2020-02-02 12:04发布

I'm trying to get my login form to only validate if only numbers were inputted. I can it to work if the input is only digits, but when i type any characters after a number, it will still validate etc. 12akf will work. 1am will work. How can i get past this?

Part of the Login

<form name="myForm">
    <label for="firstname">Age: </label>
    <input name="num" type="text" id="username" size="1">
    <input type="submit" value="Login" onclick="return validateForm()">

function validateForm()
{

    var z = document.forms["myForm"]["num"].value;
    if(!z.match(/^\d+/))
        {
        alert("Please only enter numeric characters only for your Age! (Allowed input:0-9)")
        }
}

13条回答
▲ chillily
2楼-- · 2020-02-02 12:26

Using the form you already have:

var input = document.querySelector('form[name=myForm] #username');

input.onkeyup = function() {
    var patterns = /[^0-9]/g;
    var caretPos = this.selectionStart;

    this.value = input.value.replace(patterns, '');
    this.setSelectionRange(caretPos, caretPos);
}

This will delete all non-digits after the key is released.

查看更多
放荡不羁爱自由
3楼-- · 2020-02-02 12:27

If you are using React, just do:

<input
  value={this.state.input}
  placeholder="Enter a number"
  onChange={e => this.setState({ input: e.target.value.replace(/[^0-9]/g, '') })}
/>

<div id="root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.4.2/react.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.4.2/react-dom.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.21.1/babel.min.js"></script>
<script type="text/babel">
class Demo extends React.Component {
    state = {
      input: '',
    }
    
    onChange = e => {
      let input = e.target.value.replace(/[^0-9]/g, '');
      this.setState({ input });
    }
    
    render() {
        return (
          <div>
            <input
              value={this.state.input}
              placeholder="Enter a number"
              onChange={this.onChange}
            />
            <br />
            <h1>{this.state.input}</h1>
           </div>
        );
    }
}

ReactDOM.render(<Demo />, document.getElementById('root'));
</script>

查看更多
劫难
4楼-- · 2020-02-02 12:28

Match against /^\d+$/. $ means "end of line", so any non-digit characters after the initial run of digits will cause the match to fail.

Edit:

RobG wisely suggests the more succinct /\D/.test(z). This operation tests the inverse of what you want. It returns true if the input has any non-numeric characters.

Simply omit the negating ! and use if(/\D/.test(z)).

查看更多
霸刀☆藐视天下
5楼-- · 2020-02-02 12:29

Late answer,but may be this will help someone

function isNumber(n) {
  return !isNaN(parseFloat(n)) && isFinite(n);
}

Use will be like

nn=document.forms["myForm"]["num"].value;

ans=isNumber(nn);

if(ans)
{
    //only numbers
}

This ans was found from here with huge vote

Validate numbers in JavaScript - IsNumeric()

查看更多
贼婆χ
6楼-- · 2020-02-02 12:29

The simplest solution.

Thanks to my partner that gave me this answer.

You can set an onkeypress event on the input textbox like this:

onkeypress="validate(event)"

and then use regular expressions like this:

function validate(evt){
     evt.value = evt.value.replace(/[^0-9]/g,"");
}

It will scan and remove any letter or sign different from number in the field.

查看更多
看我几分像从前
7楼-- · 2020-02-02 12:29

I think we do not accept long structure programming we will add everytime shot code see below answer.

<input type="text" oninput="this.value = this.value.replace(/[^0-9.]/g, ''); this.value = this.value.replace(/(\..*)\./g, '$1');" >

查看更多
登录 后发表回答