Проверка числа в JavaScript
Иногда данные, вводимые в текстовое поле, должны быть в правильном формате и должны быть определенного типа для эффективного использования формы. Например, номер телефона, номер рулона и т. Д. - это некоторые данные, которые должны быть в цифрах, а не в алфавитном порядке.
Подход:
Мы использовали функцию isNaN () для проверки текстового поля только для числового значения. Данные текстового поля передаются в функцию, и если переданные данные являются числом, то isNan () возвращает истину, а если данные не являются числом или комбинацией как числа, так и алфавита, то возвращает ложь.
Ниже приведен код в HTML и JavaScript для проверки текстового поля, содержит ли оно цифру или нет.
Пример:
<!DOCTYPE html><html> <head> <script> /* this function is called when we click on the submit button*/ function numberValidation() { /*get the value of the textfield using a combination of name and id*/ //form is the name of the form coded below //numbers are the name of the inputfield /*value is used to fetch the value written in that particular field*/ var n = document.form.numbers.value; /* isNan() function check whether passed variable is number or not*/ if (isNaN(n)) {/*numberText is the ID of span that print "Please enterNumeric value" if the value of inputfield is not a number*/ document.getElementById( "numberText" ).innerHTML = "Please enter Numeric value" ; return false ; } else { /*numberText is the ID of span that print "Numeric value" if the value of inputfield is a number*/ document.getElementById( "numberText" ).innerHTML = "Numeric value is: " + n; return true ; } } </script> </head> <body> <!-- GeeksforGeeks image logo--> <img src= alt= "Avatar" style= "width: 200px;" /> <!-- making the form with form tag than conatins inputField and a button --> <!-- onsubmit calls the numberValidation function which is created above --> <form name= "form" onsubmit= "return numberValidation()" > <!-- name of input type is numbers and create of id of span as numberText--> <!-- Respective output of input is printed in span field --> Number: <input type= "text" name= "numbers" /> <span id= "numberText" ></span> <br /> <input type= "submit" value= "submit" /> </form> </body></html> |
Выход:
Случай 1: текстовое поле содержит алфавиты 
Случай 2: текстовое поле содержит буквы и цифры 
Случай 3: текстовое поле содержит только цифры 