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;
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments