How to check if textbox value is not number? - javascript

<!DOCTYPE html>
<html>
<body>
<div id="text" class="CommentBox">
Some text :
<input type="text" />
</div>
<script>
$(document).ready(function () {
jQuery("#text").on("change", function () {
var x = $('#text').value;
if (isNaN(x))
{
window.alert("You have entered not a number");
return false;
});
});
});
</script>
</body>
</html>
I am trying to write javascript code to check if the given value is not number.If not i would like to give error message? If it is number I would like to check if it is integer and between 0 and 100.

Basically you need to convert to an Int before compare it with NaN which means something like:
var x = $('#text').value;
if ( isNaN( parseInt(x) ) ) {
// Not a decimal number.
}

There are a lot of syntax errors in your code.
Your selector checks your div for the change event instead of your input, which means it will never trigger the code.
You should use .val() to get the value of an element when using jQuery selectors instead of .value.
You can also use the this keyword inside the event handler to get the referenced element.
Besides that there were some misplaced ) and } in your code.
Below I have included an working sample of your code.
$(document).ready(function() {
jQuery("#text > input").on("change", function() {
var x = $(this).val();
if (isNaN(x)) {
window.alert("You have entered not a number");
return false;
} else if (x > 0 && x < 100) {
alert("number in between 0 and 100");
}
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="text" class="CommentBox">
Some text :
<input type="text" />
</div>

function numberOrNot(var input)
{
try
{
Integer.parseInt(input);
}
catch(NumberFormatException ex)
{
return false;
}
return true;
}
this will return true if your input is number, otherwise it will return false

try this code
you enter direct input on change or write id for input and pass it to javascript
$(document).ready(function() {
jQuery("input").on("change", function() {
var x = $('#text').val();
if (isNaN(x)) {
window.alert("You have entered not a number");
return false;
}
else{
if(x>=0 && x<=100)
{
window.alert("You have enter write number");
}else{
window.alert("You enter number between 0 to 100");
}
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="CommentBox">
Some text :
<input type="text" id="text" />
</div>

You can use try-catch and put as many conditions you want in try block Like this. I have put three conditions for now.
<script type="text/javascript">
function Validation(){
var number1=document.LoginForm.number1.value;
try{
if(number1==""){
throw "Empty";
}
if(isNaN(number1)){
throw "Not a Number";
}
if(number1<0 || number1>100){
throw "Out of range";
}
}
catch(err){
if (err=="Empty"){
alert("Number 1 and Number 2 fields cannot be empty");
}
if (err=="Not a Number"){
alert("Please enter a number");
}
if(err=="Out of Range"){
alert("Out of Range");
}
return false;
}
//return true;
}
</script>

Related

if and else statement condition values not being recognized

I am trying to create a block of code that takes a users input value and compares it to a random number generated when the page loads. Right now the if statement in the guess function is displaying regardless of what the value of the conditions are. If they are true it displays the first and third message and if it is wrong it also displays those two. What changes should I make to my code in order to get the if statement to alert the correct response in correlation with the users input value.
<html>
<head>
<script>
window.addEventListener("DOMContentLoaded", setup);
void setup(); {
var rNumber1 = Math.random(1-100);
var rNumber = Math.floor(rNumber1);
}
</script>
</head>
<body>
<form>
<table>
<tr><td><label>Enter Guess:</label></td><td><input id="guessedNumber" type="text" /></td></tr>
<tr><td><label>Is Correct?: </label></td><td><label id="guessResult"></label></td></tr>
<tr><td> </td><td><button type="button" onclick="guess()">Submit Guess</button></td></tr>
</table>
</form>
<script>
function guess() {
var guessedNumber = document.getElementById("guessedNumber");
if (guessedNumber != rNumber) {
alert("Your guess is incorrect. Try Again!");
} else if (guessedNumber == NaN) {
alert("Please enter a valid Number");
} else (guessedNumber == rNumber)
alert("You guessed correctly!");
}
</script>
</body>
</html>
Try:
var guessedNumber = document.getElementById("guessedNumber").value;
Also, the Math.random() method always returns a value between 0 and 1 excluding 1. It takes no parameters. Moreover, the way you have passed it parameters using the - sign will subtract the former number from the latter. The way it is used to generate a random number from 1-100 is usually:
rNumber1 = (Math.random()*100+1)
It will multiply the number times 100 and adds 1 to it which ensures that you never get 0. Also, you won't get 101 because it returns a value between 0 and 1 excluding 1.
get the value of from the input box using .value
also, i did not see any open parenthesis in the else statement, and removed the condition in else statement.
setup() is not defined anywhere so i dont know what you are trying to do with that
<html>
<head>
<script>
//window.addEventListener("DOMContentLoaded", setup);
//void setup(); {
//var rNumber1 = Math.random(1-100);
var rNumber = Math.floor(Math.random() * 100) + 1
//}
</script>
</head>
<body>
<form>
<table>
<tr><td><label>Enter Guess:</label></td><td><input id="guessedNumber" type="text" /></td></tr>
<tr><td><label>Is Correct?: </label></td><td><label id="guessResult"></label></td></tr>
<tr><td> </td><td><button type="button" onclick="guess()">Submit Guess</button></td></tr>
</table>
</form>
<script>
function guess() {
console.log(rNumber);
var guessedNumber = parseInt(document.getElementById("guessedNumber").value);
if (guessedNumber != rNumber) {
alert("Your guess is incorrect. Try Again!");
} else if (guessedNumber == NaN) {
alert("Please enter a valid Number");
} else {
alert("You guessed correctly!");
}
}
</script>
</body>
</html>

jQuery validation number

I have a single input field where the user can only enter a number between 2 AND 50. Anything above or below is invalid. It also MUST be a numeric value.
What I have so far is this:
$('#searchTimes').click(function() {
if($('#replyNumber').val()<=0) {
alert("Please select a value greater than 0 for number of guests");
$('#replyNumber').focus();
return;
}
if($('#replyNumber').val()>=51) {
alert("Please select a value less than or equal to 50 for number of guests");
$('#replyNumber').focus();
return;
}
if(isNaN($('#replyNumber').val())) {
alert("Please enter a numeric value only");
$('#replyNumber').focus();
return;
}
});
Is there a better more efficient way of writing that ^.
Also ... IF all of those IF statements are not true then I need to perform another function. How can I add that in?
_isValidNumber(number) {
var message;
var isValid;
switch(number){
case number >= 51:
message = "Please select a value less than or equal to 50 for number of guests";
isValid = false;
case number <= 0:
message = "Please select a value greater than 0 for number of guests";
isValid = false;
case isNumeric(number):
var message = "Please enter a numeric value only";
isValid = false;
default:
return true;
}
alert(message);
$('#replyNumber').focus()
return isValid;
}
function isNumeric(num){
return !isNaN(num)
}
var number = $('#replyNumber').val();
var numberIsValid = _isValidNumber(number);
I would try to abstract out duplicate code, like this:
<input id="replyNumber" >
<button id="searchTimes">click</button>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script>
$('#searchTimes').click(function() {
var val = $('#replyNumber').val()
if(val<=0) showErr("Please select a value greater than 0 for number of guests");
else if(val>=51) showErr("Please select a value less than or equal to 50 for number of guests");
else if(isNaN(val))showErr("Please enter a numeric value only");
});
function showErr(msg){
alert(msg);
$('#replyNumber').focus();
}
</script>
This is what you need :D
$('#searchTimes').on('click',function() {
var do_function = 1;
if (!$.isNumeric($('#replyNumber').val())) {
alert("Please enter a numeric value only");
$('#replyNumber').focus().select();
} else if (+$('#replyNumber').val() < 2) {
alert("Please select a value at least 2 for number of guests");
$('#replyNumber').focus().select();
} else if (+$('#replyNumber').val() > 50) {
alert("Please select a value no more than 50 for number of guests");
$('#replyNumber').focus().select();
} else {
do_function = 0;
}
if (do_function) {
call_some_function();
}
});
Good luck!
Use HTML5 min and max attributes and an input of type number (which covers the numeric part you mentioned). Use rangeOverflow and rangeUnderflow Validity Properties to check your input and present the proper error (or custom error) messages.
Try the below snippet using the following values (null (empty input),1,55) and check the custom error messages created.
function validateInput() {
var txt = "";
if (document.getElementById("inp1").validity.rangeOverflow) {
txt = "Value larger than acceptable!";
}
if (document.getElementById("inp1").validity.rangeUnderflow) {
txt = "Value smaller than acceptable";
}
if (document.getElementById("inp1").validity.valueMissing) {
txt = "Please type a number!";
}
document.getElementById("output").innerHTML = txt;
}
document.getElementById("btn").addEventListener("click", function(){
validateInput();
});
<form>
<input type="number" id="inp1" name="numberInput" min="2" max="50" required>
<button id="btn">go</button>
</form>
<div id="output"></div>

If else statement trouble javascript

My goal here is to check x and see if it is less than or equal to 100, & if it is more than or equal to 0. IF true: alert("entered grade is valid") if false: alert("entered grade is not valid").
I do not understand what i'm doing wrong, it just keeps returning any number ( for example 50, which meets both requirements) inputted as false.
my code:
<!DOCTYPE html>
<html lang="en-US">
<title> Bitar_Grade Calculator </title>
<head>
<script>
var x = document.orderForm.stuentgrade.value;
function checkGrade()
{
if (x>=0 && x<=100)
{
alert("Entered grade is valid!");
}
else
{
alert("Entered grade is invalid!");
}
}
</script>
</head>
<body>
<form>
Please enter the students grade:<br>
<input type="number" name="studentgrade"><br>
</form>
<button onclick="checkGrade()"> Enter</button>
</body>
</html>
You have some typo and errors in your code
See working function
function checkGrade() {
var x = document.getElementsByName('studentgrade')[0].value
if (x>=0 && x<=100) {
alert("Entered grade is valid!");
}
else {
alert("Entered grade is invalid!");
}
}
Try to move the reading of the form field inside the function that does the checking (and add a bit more checking for valid values), like this;
function checkGrade()
{
var x = parseInt(document.orderForm.studentgrade.value);
if (x && x>=0 && x<=100)
{
alert("Entered grade is valid!");
}
else
{
alert("Entered grade is invalid!");
}
}
However, note that this is not a full solution to validating intereg values, so somebody entering "3million" will still be validated as "3"
x is out of scope, you have no form name "orderForm", and theres a spelling mistake in your object name, stuentform...
Give your input an id, and do something like:
function checkGrade()
{
var x = document.getElementById('studentgrade').value;
if ( x>=0 && x<=100 )
{
alert("Entered grade is valid!");
}
else
{
alert("Entered grade is invalid!");
}
}

javascript validation phone number

alright, whats wrong with my script, JShint is throwing three lines of red code saying i have issues in my variable and my if/else statement. I am trying to validate if the phone number is a valid USA phone format
$( "#phone" ).focusout(function telephone() {
if( this.value === "" || this.value === null ) {
$( "#error_messages" ).text("");
return false;
} else {
var re = \d{3}[\-]\d{3}[\-]\d{4};
if(re.test(document.getElementById("phone").value)) {
$( "#error_messages" ).text("");
return true;
} else {
$( "#error_messages" ).text("Phone Number* not a valid format xxx-xxx-xxxx");
return false;
}
}
});
Firstly, you don't need a name for closure function. Secondly you have not enclosed regex with /..../.
var re = /\d{3}[\-]\d{3}[\-]\d{4}/;
You Should try this.
$(function(){
$("#phone").change(function telephone() {
if (this.value === "" || this.value === null) {
$("#error_messages").text("");
return false;
} else {
if (/\d{3}[\-]\d{3}[\-]\d{4}/.test($(this).val())) {
$("#error_messages").text("");
return true;
} else {
$("#error_messages").text("Phone Number* not a valid format xxx-xxx-xxxx");
return false;
}
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<input type="text" id="phone" />
<span id="error_messages"></span>
This is an expression tested on http://tools.netshiftmedia.com/regexlibrary/# for numbers. change it to /^\d{3}[\-]\d{3}[\-]\d{4}$/ in your JS code and apply regex code within /..../ in that tools
I applied
^\d{3}[\-]\d{3}[\-]\d{4}$
It's ok with your numbers :

How to set mobile number validation on my jsp page?

i am using this script for validation can anybody help me where i am wrong. i am using this foe mobile number validation.when i run this code with jquery it is not working.
function mobilenumber() {
if(document.getElementById('mobnum').value != ""){
var y = document.getElementById('mobnum').value;
if(isNaN(y)||y.indexOf(" ")!=-1)
{
alert("Invalid Mobile No.");
document.getElementById('mobnum').focus();
return false;
}
if (y.length>10 || y.length<10)
{
alert("Mobile No. should be 10 digit");
document.getElementById('mobnum').focus();
return false;
}
if (!(y.charAt(0)=="9" || y.charAt(0)=="8" || y.charAt(0)=="7"))
{
alert("Mobile No. should start with 9 ,8 or 7 ");
document.getElementById('mobnum').focus();
return false
}
}
}
<input type="submit" value="INSERT"class="btn"onclick="submitForm();">
jquery is
$(document).ready(function(){
function submitForm(){
if(mobilenumber()){
$('#form1').submit(function(){
});
}
else{
alert("Please Input Correct Mobile Numbers");
}
}
});
Use HTML5 Pattern
<input type="number" pattern=".{10}" title="Enter Valid Mob No" required>
var mobile = document.getElementById("mobnum").value;
var numericmob = isNumber(mobile );
if(!numericmob)
{
alert("Enter only positive numbers into the Contact Number field.");
return false;
}
if(mobile.length!=10)
{
alert("Enter 10 digits Contact Number.");
return false;
}
// write function that checks element is number or not
function isNumber(elem)
{
var re = /^[0-9]+$/;
str = elem.toString();
if (!str.match(re))
{
return false;
}
return true;
}
Advantage of this function is you can use it for checking any numeric field on your form, such as id, amount etc.
Use jQUery .submit() function to submit the form after validation is true
<form id="myForm" action="abc.php" method="post">
<!-- Your Form -->
<button onclick="submitForm();">Submit</button>
</form>
now to check if form data is valid here
function submitForm(){
if(mobilenumber()){
$('#myForm').submit();
}
else{
alert("Please Input Correct Mobile Numbers");
}
}
EDIT:
Use the #Aniket's isNumber function to check length and digit in mobile number field. Which is more generic.
if(document.getElementById('mobile_number').value != ""){
var y = document.getElementById('mobile_number').value;
if(isNaN(y)||y.indexOf(" ")!=-1)
{
alert("Invalid Mobile No.");
document.getElementById('mobile_number').focus();
return false;
}
if (y.length>10 || y.length<10)
{
alert("Mobile No. should be 10 digit");
document.getElementById('mobile_number').focus();
return false;
}
if (!(y.charAt(0)=="9" || y.charAt(0)=="8" || y.charAt(0)=="7"))
{
alert("Mobile No. should start with 9 ,8 or 7 ");
document.getElementById('mobile_number').focus();
return false
}
}
try this... this will be needful for you... and if you are looking for ragex pattern then use this....
^([0|\+[0-9]{1,5})?([7-9][0-9]{9})$

Categories