how to check input value has only numbers in angular? - javascript

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
}

Related

JavaScript prompt inputs

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();

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.

Javascript Replace - Regular Expression

I need to replace a code example: OD3 - The first must always be alpha character, 2nd alphanumeric and the last must always be numeric. What's the regular expression to check and replace the first and regulate the rest to enter correctly? A user could enter in the number 0 instead of the letter O, so I want to correct it immediately...
this is what I have so far: onkeyup="this.value=this.value.replace(/[^a-zA-z]/g,'')
First, I'd suggest just indicating the error to a user instead of replacing the values. Something like
oninput="if (! /^[a-z][a-z0-9]\d$/i.test(this.value) ) displayMessage('incorrect code');"
If you definitely have to replace the value on the fly, you could do somthing like that:
oninput='validateValue()';
...
function validateValue() {
var val = this.value;
if (! /[a-z]/i.test(val[0]) this.value = '';
else if (! /[a-z0-9]/i.test(val[1]) this.value = val.slice(0,1);
else if (! /\d/.test(val[2]) this.value = val.slice(0,2);
}
Better have like this.
onkeyup="testRegex(this.value)";
It is not .replace() it is .test()
function testRegex(value) {
if(value.test(/[^a-zA-z]/g)) {
alert("Please enter correct value");
return false;
}
}

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] : '');
}

Categories

Resources