JavaScript prompt inputs - javascript

function myFunction(){
var hours=prompt("Enter the numbers of hours:","Enter here");
if (hours<0)
{
alert("Inputs are negative. Click button to try again.");
return;
}
if (typeof(hours)!='number')
{
alert("Input not a number. Click ...");
return;
}
... more code }
I'm new to JavaScript and trying to test around with windows prompt. How can I control the input so that when the user inputs a negative number or a letter, it gives a warning alert and does not continue the function. The negative seems to work but the inputs as letters gives me errors. If I try to input a, it gives the error but at the same time, when I put in say 10, it also gives me the same error. I'm writing it specifically with windows prompt. Thanks in advance!

Input always gives a string.
You can use the build-in isNaN-function.
var hours=prompt("Enter the numbers of hours:","Enter here");
if (isNaN(hours))
{
alert("Input not a number. Click ...");
}

The value returned from prompt will be a string, so it must be converted to a number. You may use parseInt to convert the string into an integer. To check if the result is NaN, use isNaN like below.
function myFunction() {
let hours = parseInt(prompt("Enter the numbers of hours:", "Enter here"));
if (hours < 0) {
alert("Inputs are negative. Click button to try again.");
return;
}
if (isNaN(hours)) {
alert("Input not a number. Click ...");
return;
}
}
myFunction();

Related

Check if value is NaN but allow special chars

I have this validation check:
if (isNaN($scope.QuickQuoteData.RequestedAmount)) {
$scope.ShowValidation = true;
$scope.errors.push('Requested amount has invalid value.');
}
But what I want to allow is for example if user will enter values in this format:
€ 1500000
€ 1.500.000
1.500.000
Then I need to allow the operation to continue instead of throwing validation error.
So every other format will be invalid except the input values in the formats above.
Any idea how can I tweak that?
you can check with below method
if (!("Any Number with special chars".test(/^[a-zA-Z]+$/))) { ... }
This will check if provided number has String or not
will not check for Special Chars...
As my understating for your requirement, you can do somthing like this.
var specialChars=[".", "$", "€"]; //Add your symbols whatever you need.
function validate(val){
for(var i=0;i<val.length;i++){
if(specialChars.indexOf(val[i]) >= 0) {
continue;
}
if(isNaN(val[i])) {
return false;
}
}
return true;
}

Javascript: Ensure Input is Numbers Only

I have a unit conversion script; my HTML contains radio buttons (to pick the units), an input field, an output field and a button.
Here's a sample of my Javascript file:
[...]
window.addEventListener("load", function(){
document.getElementById("convert").addEventListener("click", function(){
var initial = document.getElementById("initial").value;
document.getElementById("answer").innerHTML = convertObj.converted(initial);
});
[...]
});
function ConvertClass(){}
ConvertClass.prototype.converted = function(initialAmount){
if(document.getElementById("kilograms").checked) {
this.calculation = this.multiply(initialAmount, 2.2046);
} else if(document.getElementById("pounds").checked) {
this.calculation = this.divide(initialAmount, 2.2046);
}
return this.calculation.toFixed(2);
}
[...]
var convertObj = new ConvertClass();
I would like to add something that ensures a) an empty input field isn't considered a "0", and b) something other than a number doesn't display "NaN" as the answer. In both cases, I'd simply like my output to return nothing (blank). I don't want it to do nothing, in case the user submits a blank field or an invalid value after a correct number submission (which I think would result in the previous answer still being displayed.)
How do I write that? I'm assuming I should use conditions, but I don't know which ones. I did a bit of research and apparently using isNaN() isn't entirely accurate, at least not in this context.
Where do I put the code, in the function triggered by the page load or the one triggered by the button?
I'm still learning so, if possible, I'd really appreciate explanations along with the edited code. Thank you!
Inside ConvertClass.prototype.converted at the beginning of the function, add:
// this coerces it to a number instead of a string
// or NaN if it can't convert to a number
initialAmount = initialAmount.length > 0 ? +initialAmount : 0/0;
// if not a number, return empty string
if (isNaN(initialAmount)) {
return "";
}
If the input is an empty string 0/0 evaluates to NaN.
Add the following function to check whether a value in Integer.
function isInt(value) {
return !isNaN(value) &&
parseInt(Number(value)) == value &&
!isNaN(parseInt(value, 10));
}
Change your load function like this:
window.addEventListener("load", function(){
document.getElementById("convert").addEventListener("click", function(){
var initial = document.getElementById("initial").value;
if(isInt(initial)){
document.getElementById("answer").innerHTML = convertObj.converted(initial);
}else{
document.getElementById("answer").innerHTML = '';
}
});
This will make sure that when a valid integer is supplied then only it will convert otherwise answer remain empty.
For further reading on how to check integer check this:
How to check if a variable is an integer in JavaScript?
Edit: setting answer to empty string when number not integer.

how to check input value has only numbers in angular?

I want to compare a value of a field centerCode which is entered by a user into an input field. Then I want to check if it is a number and show the appropriate alert accordingly. I am not able to compare the value or variable number with the variable code .
var numbers =/^[0-9]+$/;
var code = $scope.Nuser.centerCode;
alert(code);
if(code.val(numbers))
{
alert(code.val(numbers));
}
else
{
alert("enter numbers only");
}
You're along the right lines. Numbers needs to be a Regex though, and you need to use the test function to check the input against it. The test function will return true if the string is all numbers, or false if there is anything else in it.
var numbers = new RegExp(/^[0-9]+$/);
var code = $scope.Nuser.centerCode;
if(numbers.test(code))
{
alert('code is numbers');
}
else
{
alert("enter numbers only");
}
I would suggest you to use ng-pattern instead . Something like following :
<input type="text" ng-pattern="/^[0-9]{1,7}$/" ng-model="inputNumber"/>
It will only allow the user to enter the number.
You can use angular.isNumber to check if the entered value is a number or not. Try something like the following :
if(angular.isNumber($scope.Nuser.centerCode)){
alert('Center Code is a number');
}else {
alert('Center Code is not a number');
}
Hope this will do the trick.
You can simply convert string to number and test is it's NaN (Not a Number)
isNaN(+$scope.Nuser.centerCode)
if it's false it means your centerCode contain only numbers
try this hope this is what you are looking for
if(angular.isNumber(value))
{
//your code here
}

Check If only numeric values were entered in input. (jQuery)

I would like to check if users enter correct phone number in, with help of jQuery, so far I got to this stage:
var phone = $("input#phone").val();
if (phone !== "") {
//Check if phone is numeric
$("label#phone_error").show(); //Show error
$("input#phone").focus(); //Focus on field
return false;
}
Basically it checks if phone number was entered and if it was, I would like to check if it is a numeric value and if it is not display the error messages.
Could anyone help with checking if it is numeric?
Try this ... it will make sure that the string "phone" only contains digits and will at least contain one digit
if(phone.match(/^\d+$/)) {
// your code here
}
There is a built-in function in jQuery to check this (isNumeric), so try the following:
var phone = $("input#phone").val();
if (phone !== "" && !$.isNumeric(phone)) {
//Check if phone is numeric
$("label#phone_error").show(); //Show error
$("input#phone").focus(); //Focus on field
return false;
}
You can use jQuery method to check whether a value is numeric or other type.
$.isNumeric()
Example
$.isNumeric("46")
true
$.isNumeric(46)
true
$.isNumeric("dfd")
false
I used this to check if all the text boxes had numeric values:
if(!$.isNumeric($('input:text').val())) {
alert("All the text boxes must have numeric values!");
return false;
}
or for one:
$.isNumeric($("txtBox").val());
Available with jQuery 1.7.
http://docs.jquery.com/Plugins/Validation/CustomMethods/phoneUS
Check that out. It should be just what you're looking for. A US phone validation plugin for jQuery.
If you want to do it on your own, you're going to be in for a good amount of work. Check out the isNaN() function. It tells you if it is not a number. You're also going to want to brush up on your regular expressions for validation. If you're using RegEx, you can go without isNaN(), as you'll be testing for that anyway.
I used this:
jQuery.validator.addMethod("phoneUS", function(phone_number, element) {
phone_number = phone_number.replace(/\s+/g, "");
return this.optional(element) || phone_number.length > 9 &&
phone_number.match(/^(1-?)?(\([2-9]\d{2}\)|[2-9]\d{2})-?[2-9]\d{2}-?\d{4}$/);
}, "Please specify a valid phone number");
if (!(/^[-+]?\d*\.?\d*$/.test(document.getElementById('txtRemittanceNumber').value))){
alert('Please enter only numbers into amount textbox.')
}
else
{
alert('Right Number');
}
I hope this code may help you.
in this code if condition will return true if there is any legal decimal number of any number of decimal places. and alert will come up with the message "Right Number" other wise it will show a alert popup with message "Please enter only numbers into amount textbox.".
Thanks... :)
for future visitors, you can add this functon that allow user to enter only numbers: you will only have to add jquery and the class name to the input check that into http://jsfiddle.net/celia/dvnL9has/2/
$('.phone_number').keypress(function(event){
var numero= String.fromCharCode(event.keyCode);
var myArray = ['0','1','2','3','4','5','6','7','8','9',0,1,2,3,4,5,6,7,8,9];
index = myArray.indexOf(numero);// 1
var longeur= $('.phone_number').val().length;
if(window.getSelection){
text = window.getSelection().toString();
} if(index>=0&text.length>0){
}else if(index>=0&longeur<10){
}else {return false;} });
I used this kind of validation .... checks the pasted text and if it contains alphabets, shows an error for user and then clear out the box after delay for the user to check the text and make appropriate changes.
$('#txtbox').on('paste', function (e) {
var $this = $(this);
setTimeout(function (e) {
if (($this.val()).match(/[^0-9]/g))
{
$("#errormsg").html("Only Numerical Characters allowed").show().delay(2500).fadeOut("slow");
setTimeout(function (e) {
$this.val(null);
},2500);
}
}, 5);
});
This isn't an exact answer to the question, but one other option for phone validation, is to ensure the number gets entered in the format you are expecting.
Here is a function I have worked on that when set to the onInput event, will strip any non-numerical inputs, and auto-insert dashes at the "right" spot, assuming xxx-xxx-xxxx is the desired output.
<input oninput="formatPhone()">
function formatPhone(e) {
var x = e.target.value.replace(/\D/g, '').match(/(\d{0,3})(\d{0,3})(\d{0,4})/);
e.target.value = !x[2] ? x[1] : x[1] + '-' + x[2] + (x[3] ? '-' + x[3] : '');
}

How to check If a Tel: area code is correct using jquery?

Hy
I need to check if the given phone area code is correct.
i created a input field, user can insert a tel area code like 0044 oder 0090 and so on.
I restricted the input field to 4 chars.
I need to check after the 4 chars are entered if the area code is correct.
What it should do.
After entering 4 number, the script should check the following things.
Does the entered number equals something like "00{number 2 digit only}" if it doesnt alert("please enter correct tel areacode");
I hope i could explain my problem clear.
How can i do it with javascript or jquery?
Is "0000" a valid area code? It has "00" followed by two digits... but I assume the codes are 00 then a number 10 or higher.
$('input.phone').keyup( function(){
var num = $(this).val(), i = parseInt(num, 10), valid = true;
if(num.length==4 && (i<9 || i>99) ){
//phone number is invalid
}
});
But I think that blur event will be more useful here, because the above function wouldn't notify the user if he typed only three digits. Notification will appear as soon as the focus is moved aout of the input box, not as soon as the fourth digit was typed. So my proposition is:
$('input.phone').blur( function(){
var num = $(this).val(), i = parseInt(num, 10), valid = true;
if(num.length != 4 || i<9 || i>99 ){
//phone number is invalid, notify the user
}
});
edit: I thought you're validating some kind of area codes specific to your coutry. If you want to validate international calling codes you may wish to look at this list: http://en.wikipedia.org/wiki/List_of_country_calling_codes - there are many +XXX (or 00XXX) numbers and these won't fit into your 4 characters long input. And many numers aren't in +XX (00XX) format, like +1 (001) for USA. I think you should just check if it's + or 00 followed by at least one digit other than zero and let it in.
/^(\+|00)[1-9]/.test( input.value );
Something like this should work:
$('#field').keyup(function() {
var value = $(this).val();
// Restrict length to 4 characters
if(value.length > 4) {
value = value.substring(0, 3);
$(this).val(value);
}
// Test is value equals to "00{number 2 digit only}"
if(/00\d{2}/.test(value)) {
// Is valid
} else {
// Not valid
}
});
I'd avoid using alert on the not valid part, as that would give the user an alert box every time he presses a key.

Categories

Resources