I have a simple if statment in a verify function that check at least 10 numbers are used in a field
function verfiyFields() {
var flag = true;
var number = $atj('#interested-number-form');
if(number.val().replace(/\s+/g, '').length < 10){
number.parent().prepend('<p class="form-error">Please enter phone number</p>');
fadeOut();
flag = false;
}
return flag;
}
How can I also check that only numbers are used.
You could use .match(/^\d+$/) to check if there are only digits.
var value = number.val().replace(/\s+/g, '');
if (value.length >= 10 && value.match(/^\d+$/)) {
// ..
}
You can also check if there are at least 10 digits using the regular expression /^\d{10,}$/ and avoid checking the length property:
var value = number.val().replace(/\s+/g, '')
if (value.match(/^\d{10,}$/)) {
// ..
}
As a side note, you can also use the pattern attribute:
<form>
<input type="text" pattern="^\d{10,}$" />
<input type="submit" />
</form>
function verfiyFields() {
var reg = /^\D*(?:\d\D*){10}$/;
var number = $atj('#interested-number-form');
var flag = reg.test(number.val())
if (!(flag)) {
number.parent().append('<p class="form-error">Please enter a valid 10 digit phone number</p>');
}
return flag;
}
Use RegExp.test(str) to check to make sure that the length of the field excluding all characters that are not digits is 10. RegExp.test returns a true or false value so this can be the flag you return.
RegExp.test(str) Documentation
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/test
Demo:
http://jsfiddle.net/SeanWessell/1v6vnath/
Related
I need a field which can only take numbers, but not allow for signs such as "+", "-", "*" and "/". 0 can also not be the first number. If I make an Input field and set it's type to "number" I'm still allowed to write at least "+" and "-", and I can't quite seem to prevent the user from writing 0 as the first number either.
$('input#update-private-ext').on('keydown', function (e) {
var value = String.fromCharCode(e.keyCode);
if ($(this).text.length == 0 && value == 0) {
return false;
}
});
The above was my first attempt at making the function disallow 0 as the first character, but it doesn't seem to work. It just lets me write 0 as the first character. I also tried this to stop the signs from showing up:
$('input#update-private-ext').on('keydown', function (e) {
var badChars = '+-/*';
var value = String.fromCharCode(e.keyCode);
if ($(this).text.length == 0 && value == 0) {
return false;
}
if (badChars.indexOf(value) == -1) {
return false;
}
});
But with the badChars check, I cannot write anything in my field. So what am I missing here?
You should use e.key to get the current key pressed. String.fromCharCode(e.keyCode) gives the wrong result.
Also you should check if the bad chars is not -1. If it is, then your char is not a bad character and so you should not enter the if.
If you want to get the length of the input field you should use jQuery's .val() and not .text(). Or you can simply do it without jQuery using this.value.length.
$('input#update-private-ext').on('keydown', function (e) {
var badChars = '+-/*';
var value = e.key;
if (this.value.length == 0 && value == '0') {
return false;
}
if (badChars.indexOf(value) !== -1) {
return false;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="update-private-ext">
When you compare numbers and strings you must remember that numbers are encoded by using character codes from 48 to 57 and comparing strings with numbers is error-prone in JavaScript as there are many implicit coercions. You should be comparing objects of the same type to avoid the confusion.
In your case, the comparison should be done in the way that parsed string from the String.fromCharCode equals '0' - zero character (string), not the 0 as a number.
There are also issues of the keyCode parsing which yield strange values for the symbols because you would have to manually consider if Shift and other meta keys are pressed when parsing. Save yourself a trouble and just use e.key to get parsed key value.
By the way, please see the difference between this and $(this). Basically, in your case, it means that real instance of the input field is the first element of JQuery iterator - $(this)[0]. You may then just use this, which is automatically set to the target element in the event handler.
Please see the following example of blocking first 0 with debug information printed out:
$('input#update-private-ext').on('keydown', function (e) {
var value = e.key;
console.log('Typed character:');
console.log(value);
console.log('$(this)');
console.log($(this));
console.log('this (input element):');
console.log(this);
console.log("input's value:");
console.log(this.value);
if (this.value.length == 0 && value == '0') {
console.log('blocked');
return false;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="update-private-ext" />
In order to block other characters you can just filter them the following way (remember that indexOf returns -1 when the index is not found):
$('input#update-private-ext').on('keydown', function (e) {
var badChars = '+-/*';
var value = e.key;
if (this.value.length == 0 && value == '0') {
return false;
}
//Please note NOT EQUALS TO -1 which means not found.
if (badChars.indexOf(value) !== -1) {
return false;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="update-private-ext" />
You can do something like this below:
1. Check for bad chars if badChars.indexOf(v) >= 0.
2. Disallow starting from 0 by checking if the input starts from 0 and if yes, set the input field to blank.
This can give you a start!
$('input#update-private-ext').on('keydown', function(e) {
var badChars = '+-/*';
var v = e.key;
if (badChars.indexOf(v) >= 0) {
return false;
}
if ($(this).val().startsWith('0')) {
$(this).val("");
return false;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="update-private-ext" />
I am trying to implement a validation check for an input text control which should allow only a positive integer value or a float with maximum 2 decimal places.
Here is the fiddler with the approaches I've tried: https://jsfiddle.net/99x50s2s/49/
HTML
Enter Price: <input type="text" id="price"/> (Example: 10, 10.50. Do not include $ symbol.)
<br/>
<br/>
<button type="button" id="check1">Check Method 1</button> (Fails when the value is 1.00)
<br/>
<br/>
<button type="button" id="check2">Check Method 2</button> (Passes when the value is 45f)
<br/>
<br/>
<button type="button" id="check3">Check Method 3</button> (Passes when the value is -10)
Code:
var price = $('#price');
$('#check1').on('click', function(){
var val = $.trim(price.val());
var num = Number(val);
if (String(num) === val && num >= 0)
{
alert('Valid');
}
else
{
alert('Invalid');
}
});
$('#check2').on('click', function(){
var val = $.trim(price.val());
var num = Number(val);
if (((typeof num === 'number') && (num % 1 === 0)) || parseFloat(val))
{
alert('Valid');
}
else
{
alert('Invalid');
}
});
$('#check3').on('click', function(){
var val = $.trim(price.val());
if ($.isNumeric(val))
{
alert('Valid');
}
else
{
alert('Invalid');
}
});
Expectation:
The values that should be passed are positive numbers and float with maximum 2 decimals. (example 10, 10.50)
I looked at various answers in stackoverflow but non matched with my expectation. Any help is appreciated.
What you are really looking for is that the value matches a pattern, not what it's value is. For that, you are probably best off using a regular expression. Specifically, this should catch the value that you are looking for:
/^\d+(\.\d{1,2})?$/
That says:
starting at the beginning of the value (^)
match 1 or more digits (\d+)
followed by an option decimal point and 1 or two digits ((\.\d{1,2})?)
and no other characters before the end of the value ($)
That should enforce all of your rules, allowing you to perform a single check for validity, rather than multiple ones.
Edit: Here is an example of how to use it:
function checkNumber(sNum) {
var pattern = /^\d+(\.\d{1,2})?$/;
console.log(sNum + " is " + ((pattern.test(sNum)) ? "" : "not ") + "valid.");
}
checkNumber("1"); // 1 is valid.
checkNumber("-1"); // -1 is not valid.
checkNumber("1234"); // 1234 is valid.
checkNumber("1."); // 1. is not valid.
checkNumber("1.0"); // 1.0 is valid.
checkNumber("1.12"); // 1.12 is valid.
checkNumber("1.123"); // 1.123 is not valid.
I would imagine it would be:
var num = Number(val);
if (!isNaN(num)
&& num > 0
&& num == num.toFixed(2))
{
// Valid
}
This question already has answers here:
Simple regular expression for a decimal with a precision of 2
(17 answers)
Closed 9 years ago.
i Want to validate a text field in keyup event .
in the field it should accept money type decimal like
(12.23)
(.23)
(0.26)
(5.09)
(6.00)
if i enter some wrong value then it should return to the previous value and remove the wrong one
I think something like this might be your best bet
var isValidCurrency = function(str) {
var num = parseFloat(str);
return !Number.isNaN(num) && num.toFixed(2).toString() === str;
};
Some tests
isValidCurrency("1234.56"); // true
isValidCurrency("1234.565"); // false
isValidCurrency("1234"); // false
isValidCurrency("foo"); // false
You can use following Regex
val = "2.13"
if (!val.match(/^(\d{0,2})(\.\d{2})$/)) {
alert("wrong");
} else {
alert("right");
}
http://jsfiddle.net/rtL3J/1/
EDIT
Please note that if the numbers preceding dot (.) has limit of length to two then the code valid code is
^(\d{0,2})(\.\d{2})$
else if there is no limit then just remove the 2 from the code i.e.
^(\d{0,})(\.\d{2})$
Try this:
function evMoneyFormat(evt) {
//--- only accepts accepts number and 2 decimal place value
var theEvent = evt || window.event;
var key = theEvent.keyCode || theEvent.which;
key = String.fromCharCode(key);
var regex = /^[0-9]{1,14}\.[0-9]{0,2}$/; // number with 2 decimal places
if (!regex.test(key)) {
theEvent.returnValue = false;
//--- this prevents the character from being displayed
if (theEvent.preventDefault) theEvent.preventDefault();
}
}
The control:
<input type='text' onkeyup='evMoneyFormat( e );'>
Try following code
function validateDecimal(num){
var dotPosition=num.indexOf(".");
if(dotPosition=="-1"){
document.getElementById('cost').value= num+".00"
}
}
And in html
<input type="text" id='cost' onkeyup="validateDecimal(this.value)" />
I'm trying to validate a form input value. The function below states is the value of the input is a number below 150, show error. Works as it should. However, I want to add to it. If the value contains ANYTHING other than a numeric value AND/OR is a value under 150, show error...
How can I modify?
if ($('.billboard-height').val() < 150) {
$('.sb-billboardalert').fadeIn(600);
}
Since your more thorough validation should be on the server-side anyway, you could just use parseInt or parseFloat depending on what sort of value you are expecting. Then check if the result is actually a number and that it also meets your constraints:
var number = parseFloat($('.billboard-height').val()); // or parseInt depending on expected input
if (isNaN(number) || number < 150) {
$('.sb-billboardalert').fadeIn(600);
}
EDIT:
Based on your comments, you are entering regex land. I gather you only ever want a natural number (and the way parseInt/parseFloat ignores trailing non-numeric characters like px, em, etc. is not ok). How about:
var val = $('.billboard-height').val();
var number = parseInt(val, 10);
if ( ! val.match(/^[0-9]{3,4}$/) || number < 150) {
$('.sb-billboardalert').fadeIn(600);
}
This should only allow natural numbers 150-9999.
I would suggest using regexes:
var intRegex = /^\d+$/;
var floatRegex = /^((\d+(\.\d *)?)|((\d*\.)?\d+))$/;
var str = $('#myTextBox').val();
if(intRegex.test(str) || floatRegex.test(str)) {
alert('I am a number');
...
}
Or with a single regex as per #Platinum Azure's suggestion:
var numberRegex = /^[+-]?\d+(\.\d+)?([eE][+-]?\d+)?$/;
var str = $('#myTextBox').val();
if(numberRegex.test(str)) {
alert('I am a number');
...
}
ref: checking if number entered is a digit in jquery
Don't forget the radix parameter in parseInt():
if (parseInt($('.billboard-height').val(), 10) < 150) {
It's probably faster than using a regex. Regular expressions are not known for being fast, but they are very powerful. It might be overkill for this scenario.
You can try out HTML5's built in form validation:
<input type="number" min="150">
browser support is still pretty shakey though
Any value from an input or select will be a string in javascript. You need to use parseInt() to use operators like > or <. == can be used if you use it to compare to a string like if ($('.billboard-height').val() == "150")
Try parseInt and isNaN functions for check if value is number and less than 150:
var intVal = parseInt($('.billboard-height').val());
if(!isNaN(intVal)){ //not Number
if (parseInt($('.billboard-height').val()) < 150) { //not less than 150
$('.sb-billboardalert').fadeIn(600);
}
}
If you need to support floating point numbers, you can check if a variable is valid using:
function isNumber (n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
var val = $('.billboard-height').val();
if (isNumber(val) && parseFloat(val) < 150) {
$('.sb-billboardalert').fadeIn(600);
}
If you only need to support integers, use parseInt(n, 10), where 10 is the base to convert the string to.
var val = parseInt($('.billboard-height').val(), 10);
if (val && val < 150) {
$('.sb-billboardalert').fadeIn(600);
}
// Displays an alert if s contains a non-numeric character.
function alertForNonNumeric(s) {
var rgx = /[^0-9]/;
if (s.search(rgx) !== -1) {
alert("Input contains non-numeric characters!");
}
}
JS Fiddle here
NOTE: If you want to check for negative ints as well, you can add a minus sign to the regex:
function alertForNonNumeric(s) {
var rgx = /[^0-9-]/;
if (s.search(rgx) !== -1) {
alert(s + " contains non-numeric characters!");
}
}
I use this solution, I find it quite ellegant - no alerts, user is effectively unable to enter non numeric characters.
This is jQuery example:
function digitsOnly(){
// extract only numbers from input
var num_val = $('#only_numbers').val().match(/\d+/);
$('#only_numbers').val(num_val);
}
Your html:
<input type="text" name="only_numbers" id="only_numbers" on oninput="digitsOnly();"/>
I've am using jQuery validation plugin to validate a mobile phone number and am 2/3 of the way there.
The number must:
Not be blank - Done,
Be exactly 11 digits - Done,
Begin with '07' - HELP!!
The required rule pretty much took care of itself and and I managed to find the field length as a custom method that someone had shared on another site.
Here is the custom field length code. Could anyone please suggest what code to add where to also require it begin with '07'?
$.validator.addMethod("phone", function(phone_number, element) {
var digits = "0123456789";
var phoneNumberDelimiters = "()- ext.";
var validWorldPhoneChars = phoneNumberDelimiters + "+";
var minDigitsInIPhoneNumber = 11;
s=stripCharsInBag(phone_number,validWorldPhoneChars);
return this.optional(element) || isInteger(s) && s.length >= minDigitsInIPhoneNumber;
}, "* Your phone number must be 11 digits");
function isInteger(s)
{ var i;
for (i = 0; i < s.length; i++)
{
// Check that current character is number.
var c = s.charAt(i);
if (((c < "0") || (c > "9"))) return false;
}
// All characters are numbers.
return true;
}
function stripCharsInBag(s, bag)
{ var i;
var returnString = "";
// Search through string's characters one by one.
// If character is not in bag, append to returnString.
for (i = 0; i < s.length; i++)
{
// Check that current character isn't whitespace.
var c = s.charAt(i);
if (bag.indexOf(c) == -1) returnString += c;
}
return returnString;
}
$(document).ready(function(){
$("#form").validate();
});
The code in the question seems a very complicated way to work this out. You can check the length, the prefix and that all characters are digits with a single regex:
if (!/^07\d{9}$/.test(num)) {
// "Invalid phone number: must have exactly 11 digits and begin with "07";
}
Explanation of /^07\d{9}$/ - beginning of string followed by "07" followed by exactly 9 digits followed by end of string.
If you wanted to put it in a function:
function isValidPhoneNumber(num) {
return /^07\d{9}$/.test(num);
}
If in future you don't want to test for the prefix you can test just for numeric digits and length with:
/^\d{11}$/
You could use this function:
function checkFirstDigits(s, check){
if(s.substring(0,check.length)==check) return true;
return false;
}
s would be the string, and check would be what you are checking against (i.e. '07').
Thanks for all the answers. I've managed to come up with this using nnnnnn's regular expression. It gives the custom error message when an incorrect value is entered and has reduced 35 lines of code to 6!
$.validator.addMethod("phone", function(phone_number, element) {
return this.optional(element) || /^07\d{9}$/.test(phone_number);
}, "* Must be 11 digits and begin with 07");
$(document).ready(function(){
$("#form").validate();
});
Extra thanks to nnnnnn for the regex! :D
Use indexOf():
if (digits.indexOf('07') != 0){
// the digits string, presumably the number, didn't start with '07'
}
Reference:
indexOf().