简体   繁体   中英

Regular expression for ten digit number

My program here is trying to have the user input in a text field, and if the user input is a 10-digit number(numbers with 0's at the beginning or any of that sort count) when they press the check button they will receive an alert saying what their number is, or otherwise they will receive an alert telling them to enter a proper number.

However, whenever I press the button, nothing changes. I believe that there is a problem inside my regular expression and the function, but I am not sure how to write a regular expression that searches for a particular pattern where there are 10 digits in the result of a form.

Here are the relevant bits of my code.

<form name = submitnumber">
  <input type = "text" size = "15" name = "inputnumber"></input>
  <button type = "button    " onclick = "checknumber()">Check</button>
</form>
<script type "text/javascript">
  function checknumber() {
    var tendigitnum = /^\d+${10}/; 
    var input_num = document.getElementByName("inputnumber")
    if (input_num.search(tendigitnum)) {
      window.alert("You entered: " + input_num);
    } else {
      window.alert("Please enter a valid 10 digit number!");
    }
  }
</script>

Your regex's syntax is wrong.

Make it

var tendigitnum = /^\d{10}$/; 

and use it as

tendigitnum.test("2342343434"); //outputs true

Also, there is no such method as getElementByName , you need to use getElementsByName and returns multiple elements. Make it

var input_num = document.getElementsByName("inputnumber")[0].value;

You need to change the regex to a valid one

var tendigitnum = /^\d{10}$/;

and the right access to the element's value with

document.getElementsByName("inputnumber")[0].value

and you need to perform a match with

if (input_num.match(tendigitnum)) {
    //
}

 function checknumber() { var tendigitnum = /^\\d{10}$/; var input_num = document.getElementsByName("inputnumber")[0].value; if (input_num.match(tendigitnum)) { alert("You entered: " + input_num); } else { alert("Please enter a valid 10 digit number!"); } } 
 <form name = submitnumber"> <input type="text" size="15" name="inputnumber"></input> <button type="button" onclick="checknumber()">Check</button> </form> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM