How to check if a textbox contains numbers only?
While googling I came across this. But I'm wondering if isNumeric can be used for this purpose or if there are more simpler ways of checking if a textbox has a numeric value.
var query = $('#myText').val();
if (parseFloat(query) == NaN) {
alert("query is a string");
} else {
alert("query is numeric");
}
You can check if the user has entered only numbers using change event on input and regex.
$(document).ready(function() {
$('#myText').on('change', function() {
if (/^\d+$/.test($(this).val())) {
// Contain numbers only
} else {
// Contain other characters also
}
})
});
REGEX:
/: Delimiters of regex
^: Starts with
\d: Any digit
+: One or more of the preceding characters
$: End
Regex Visualization:
Demo
If you want to allow only numbers, you can use input-number and pattern
<input type="number" pattern="\d+" />
using pure JS regular expression
var query = document.getElementById('myText').value;
var isNumeric=query.match(/^\d+$/);
if(isNumeric){/*...*/}else{/*...*/}
or using html5 control
<input type="number" name="quantity" min="1" max="5">
There're many ways, you can use isNaN
isNaN(VALUE);
You can also use regEx to verify numeric values.
console.log(/^\d+$/.test(VALUE));
Jquery provides generic util method to handle this.
handles numeric/float/hex
$.isNumeric( value )
Try: fiddle
You can match the value of text box against the numeric regression to check if it contains numbers only or not, Like below code...
if($('#myText').val().match(/^\d+$/)){
// Your code here
}
Related
I am using input type number and It's preventing character but it's unable to prevent plus, minus symbol or character. But I require to prevent all symbol.
<input type="number">
I have worked on it and create my customise regex and it's working fine but I want to know why it's working like that for input type number and how we can fix that.
You can do this using jquery
$('input').keypress(function (e) {
var txt = String.fromCharCode(e.which);
if (!txt.match(/[0-9]/)) {
return false;
}
});
Because that's exactly how the spec says it should work. The number input can accept floating point numbers, including negative symbols and the e or E character:
A floating-point number consists of the following parts, in exactly
the following order:
Optionally, the first character may be a "-" character.
One or more characters in the range "0—9".
Optionally, the following parts, in exactly the following order:
a "." character
one or more characters in the range "0—9"
Optionally, the following parts, in exactly the following order:
a "e" character or "E" character
optionally, a "-" character or "+" character
One or more characters in the range "0—9".
You can do it with simple and a minimum limit for your number. Something like this:
<input min="0" type="number" step="1">
Now adding + or - signs make field value invalid and step=1 is for when you only need unsigned integers. If you don't need that, simply remove it.
Edit
If you don't want to + and - signs show in the filed, plus don't accept that input, you need to use some js.
Here is the simplest pure js solution I think:
Your html code:
<input min="0: type="number" step="1" onkeypress="removeSigns()" id="my-input">
And now you need to add this little script to your page:
function removeSigns() {
var input = document.getElementById('my-input');
input.value = parseInt(input.value.toString().replace('+', '').replace('-', ''))
This script gets the element that has my-element id, then overwrite its value.
The new value is int version of old value after replacing + and - signs in it with an empty string(removing them from the string in reality).
This solution is good when you only have one input, if you had more number input, you should change the removeStrin to a version that gives input object from this in the onkeypress. But I don't add that version because of simplicity of the solution.
}
How would I format a number like: (99) 9999-9999 into: 9999999999 using angularjs? someone told me to use phoneformat.js but I don't know how to implement it in my project
I'm not sure that you need anything special from Angular or any special libraries . . . just use the basic JS .replace() method and a little regex:
var sPhoneNum = "(99) 9999-9999";
var sFormattedPhoneNum = sPhoneNum.replace(/\D/g, "");
// sFormattedPhoneNum equals "9999999999"
The regular expression /\D/g matches all non-numeric characters, so it will strip out everything but the numbers.
so like talemyn said... the solution is simply to remove the unwanted char... the angular way to do it is via filter I guess... this is a jsfillde
with an example...
myApp.filter('phoneToNum', function() {
return function(input, scope) {
return input.replace(/\D/g, "");
}
});
now if you also want to revert it... use
phone filter
Try this:
formatLocal('US', phoneNumber)
I had an input field where I needed to get phone number from users but only the digits so that it's easy to index using phone number in the database. I used .replace on ng-keyup, so the non-digit characters gets removed as the user types.
in html
<input ng-keyup="formatNum()" ng-model='data.phone' placeholder="Phone Number" />
in controller
$scope.formatNum = function() {
if ($scope.data.phone)
$scope.data.phone = $scope.data.phone.replace(/\D/g, "");
};
$('#target').val($('#target').val().replace(/[^\d]/g, ""));
I use the above code to leave only numeric characters in an input value I would also like to allow '+' and '-'.
How would I modify the regex to allow this?
Help much appreciated
Put - and + in the character class.
$('#target').val($('#target').val().replace(/[^-+\d]/g, ""));
FWIW I use a couple of input classes that I control with jQuery:
<input class="intgr">
<input class="nmbr">
$("input.intgr").keyup(function (e) { // Filter non-digits from input value.
if (/\D/g.test($(this).val())) $(this).val($(this).val().replace(/\D/g, ''));
});
$("input.nmbr").keyup(function (e) { // Filter non-numeric from input value.
var tVal=$(this).val();
if (tVal!="" && isNaN(tVal)){
tVal=(tVal.substr(0,1).replace(/[^0-9+\.\-]/, '')+tVal.substr(1).replace(/[^0-9\.]/, ''));
var raVal=tVal.split(".")
if(raVal.length>2)
tVal=raVal[0]+"."+raVal.slice(1).join("");
$(this).val(tVal);
}
});
intgr strips all non-numeric
nmbr accepts +, -, . and 0-9. The rest of the string gets stripped of all but 0-9 and the first . If you are OK with the + and - being anywhere, Bamar's solution is perfect, short and sweet. I needed the +/- to be only in the first character position if at all, and only one . (i.e. strip out beyond the first period so 2.5.9 would be 2.59)
I have a textbox whereby the user needs to input his/her mobile number. However I need to validate the first 2 numbers (characters) to make sure that the mobile number is in the correct format (as one of the validation rules).
The mobile number needs to start with any of the following 2 digits:
44xxxxxx
55xxxxxx
65xxxxxx
78xxxxxx
Can anyone tell me how it's possible to validate the first two characters number and check that they are either one of the options mentioned above?
EDIT
This is what I had tried but it did not work:
HTML
<input id="mob" name="mob" type="tel" placeholder="Enter your mobile number">
Validate
JS
var mobile_prefix = $('#mob').subsubstr(0,2);
$('#validate').click(function(){
if (mobile_prefix == 44||55||65||78) {
alert('correct');
}
else {
alert('incorrect');
}
});
I think .match() has what you're looking for. Just brush up on some regular expressions.
if (StringFromSelectField.match(/^(44|55|65|78)/)) {
//do something
}
Use substring from javascript
var FirstTwoLetters = TextFromYourInput.substring(0,2);
and then you can compare first two letters with your pattern.
Using a regular expression would probably be the easiest:
({phone number}).match(/^(44|55|65|78).*$/)
So first variable for input filed;Kind of my way;)
first check if that input is not empty and has 3 or more signs.
On the end is variable which I use on the end to allow form.submit().
If you want you can add before each getting val() $.trim(postcode.val()) != ''
var postcode = $('#post_code');
if(postcode.val() != '' && postcode.val().length > 2){
var shortPostCode = postcode.val().substring(0,2);
var validPostCode = /^(EH|KY)/;
if(!shortPostCode.match(validPostCode)){
postcode.after('<span class="error">Post code must start with EH</span>');
dataValid = false;
}
}
I have a text box and it says "Phone:" as the standard here for phone number is (XXX)-XXX-XXXX
I'd like to have a javascript that automatically puts my numbers into that format if it's not in that format, so if you typed 9993334444 then it would change it automatically on the fly as I'm typing to (999)-333-4444 I have looked around Google for Javascript Phone Regex to no success, maybe a Regex isn't what I'm looking for?
you want to add an onkeyup event with a regex like
this.value = this.value.replace(/^\(?([0-9][0-9][0-9]){1}\)?-?([0-9][0-9][0-9][0-9]){1}-?([0-9][0-9][0-9]){1}$/, '($1)-$2-$3');
Check out http://jsfiddle.net/R8enX/
/ means start/end a regex string
^ means start of matching string
$ means end of matching string
? means 0 or 1 instances (make braces and dashes optional)
[0-9] means any single digit
(x){1} tags x as an expression that we can reference in the replacement with a $ sign
EDIT: realized I missed a digit on the last group of numbers, the jsfiddle will only work (properly) with 3 digits in the last group
To build somewhat on #Andrews answer you can check for a valid (local)phone number via this method. If the number is shorter or larger than 10 digits, it collapses back into an invalid number
-
<input type="text" onBlur="localNumber(this.value)"/>
<div id="output"></div>
-
<script>
var localNumber = function(str){
repl = str.replace(/^([0-9]{3})([0-9]{3})([0-9]{4})$/, "($1)-$2-$3");
outp = document.getElementById('output');
if( repl.match(/\W/) )
{
outp.innerHTML = repl;
}
else
{
outp.innerHTML = 'Invalid number for this region';
}
}
</script>