I'm working on a project that has an input field requiring user to enter only any of the following three options:
Number like 150
Number starting with one letter (which must be N, not case sensitive) like N150
Number ending with one letter (which must be N, not case sensitive) like 150N
Any other value like:
150x will return error message wrong input
x150 will return wrong input
1N50 will return wrong position
The correct way to do this is to make an array of valid numbers and then to check if the given text exists on your array.For example:
var validNumbers = [ 150, N150, 150N ];
if (validNumbers.indexOf(parseInt(num, 10)) >=0 ) {
//Match
}
You'll need an indexOf function for IE:
if (!Array.prototype.indexOf) {
Array.prototype.indexOf = function(needle) {
for(var i = 0; i < this.length; i++) {
if(this[i] === needle) {
return i;
}
}
return -1;
};
}
check this answer :
Regular expression to match a number range in JavaScript
and adjust to your needs, you can easily add the "N" at the end or at the beginning by adding regex part to make accept values like :
-N150
-150N
-130N
-N130
A non regexapproach (just to show why regex is useful):
function test(value){
//convert to array
value=value.split("");
//check the number
function isnumber(num){
return num.every(n=>"1234567890".includes(n));
}
//weve got three possibilities:
//150
if(isnumber(value)) return true;
//N150
var [n,...rest]=value;
if(n==="N" && isnumber(rest)) return true;
//150N
var n=value.pop();
return n==="N" && isnumber(value);
}
http://jsbin.com/kafivecedi/edit?console
Related
Hi guys i got a problem here, how i can validate a password box that must contain at least one numeric character. i'm not allowed using regular expression / regex. i have tried searching over the web, but the solution is always end with regex.
here's my code that i try
function validateIn()
{
var pass=document.getElementById('password').value;
for(var i=0;i<pass.length;i++)
{
if(isNaN(pass.charAt(i))==false)
{
return true;
break;
}
else
{
return false;
}
}
}
i have tried that way but i fail, can u help me guys? thanks before
One possible approach:
function validateIn() {
var pass = document.getElementById('password').value,
p = pass.length,
ch = '';
while (p--) {
ch = pass.charAt(p);
if (ch >= '0' && ch <= '9') {
return true; // we have found a digit here
}
}
return false; // the loop is done, yet we didn't find any digit
}
The point is, you don't have to return immediately after you have found a normal character (as you're basically looking for a single digit) - you just have to move on with your checking.
Note that I have gone without isNaN, as it's a bit inefficient: the only thing required is a range check.
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().
I keep getting a result of 0 whenever I type in a search term. I'm trying to find the number of times that a pattern occurs in string. So for example searching for at would return 3. Any advice on where I'm going wrng?
string =
[
"cat math path"
]
var pattern = prompt('Please enter a search term:');
function check(string,pattern)
{
if(pattern)
{
if(pattern.indexOf(string) == -1)
{
return 0;
}
return count(pattern.substring(pattern.indexOf(string)+string.length), string)+1;
}
else
{
return("Nothing entered!");
}
}
alert(check(string,pattern));
if(pattern.indexOf(string) == -1)
should be
if(string.indexOf(pattern) == -1)
I think you inverted the use of pattern and string. See the documentation of indexOf. Also you can easily count occurrences with split which breaks your string into an array:
count=string.split(pattern).length - 1;
Where string="cat math path"; (instead of an array)
I have to do image size validation using JavaScript. The sizes are provided as text, in the form nXn — e.g. “5X4” or something.
I have done a test for whether the provided size contains an “X”:
if(inputVal.indexOf("X")==-1)
{
$('#erSize').append("*Size should be (e.g) 6X4");
}
But this test accepts e.g. “aXg” also.
How can I check that the values entered either side of "X" are only integers?
Use Regular Expressions
var pattern = /[0-9]\X[0-9]/;
inp = "AXG"; //Sample
if(!pattern.test(inp))
alert("Error");
http://jsfiddle.net/hFTJb/
if(/^\d+X\d+$/.test(inputVal)) // add i after the pattern to match x case-insensitive
{
$('#erSize').append("*Size should be (e.g) 6X4");
}
// accepts "1X1"
// accepts "9999X9999"
// rejects "aaa1X1aaa"
RegEx is probably the best way, I'll give "raw" example without regular expressions that is doing the same thing:
function ValidateImageSize(imgSize) {
var arrDimensions = imgSize.toUpperCase().split("X");
if (arrDimensions.length != 2)
return false;
var w = arrDimensions[0] * 1;
var h = arrDimensions[1] * 1;
return !isNaN(w) && !isNaN(h) && w > 0 && h > 0;
}
Usage:
if (!ValidateImageSize(inputVal)) {
$('#erSize').append("*Size should be (e.g) 6X4");
}
Giving it as it's more readable than RegEx and you can control and understand each step.
Live test case.
You can easily do that by using the RegEx.
Use the regular expression as /(\d+)X(\d+)/g
function isValidInput() {
var regex = new RegExp(/(\d+)X(\d+)/g);
var match = regex.exec(inputVal);
if (match == null) {
$('#erSize').append("*Size should be (e.g) 6X4");
} else {
// here 'match' will be an array of 2 numeric values [D,D] where d is an integer.
}
}