regex for javascript pattern match - javascript

i'm looking for a regex expression or javascript which alerts me when a number is NOT between 48-47 or NOT between 96-105 or IS NOT 110 OR 190 OR 8 OR 13.
thanks for all the help friends !!

Regex is not appropriate for such specific numeric checks. Just do a few if statements to compare the value you're working with to the specific values and ranges you want to exclude.
var number = 19;
alert('Number is'+(numberIsValid(number) ? 'valid' : 'not valid'));
function numberIsValid(number) {
// test for numeric argument
if ((number - 0) != number)
return false;
// test for specific exclusions
if (number == 110 || number == 190 || number == 8 || number == 13 || number == 48 || number == 47)
return false;
// test for excluded range
if (number >= 96 && number <= 105)
return false;
return true;
}

I agree with Chris's response above, if you want to see what it would look like, it is kind of a mess. I wouldn't really recommend you use this.
Just to rephrase: Number may not be 8,13,47,48,96-105,110
var num = 10;
if (! /^(8|13|47|48|9[6-9]|10[0-5]|110)$/.test(num)) {
alert(num);
}

function allowedIntegers(n){
return !/^([^\d]|8|13|47|48|110|190|96|97|98|99|100|101|102|103|104)$/.test(String(n));
}

Related

Check for 4 numbers before decimal and 1 number after decimal

I have an input number field which should allow max 4 numbers before decimal and max 1 number after decimal or upto 6 numbers without decimal.
E.g. Valid 1.2, 113.5, 1234.5, 456789.
I used this RegEx ^\d{0,4}\.?(\.\d{0,1})?$ on keypress. It works fine, but gives false only after displaying the number like 113.55. How can I solve this?
My Keypress Function:
function OnKeyPress(e,DivID) {
if ( e.which != 8 && e.which != 0 && e.which != 13 && e.which != 46 && (e.which < 48 || e.which > 57)) {
return false;
}
var val = j$('[id$='+DivID+']').val();
if(DivID == 'ProximityCPPercentage')
{
var x = event.which || event.keyCode;
if(val.indexOf('.') >= 0 && e.which == 46)
return false;
else if(e.which == 46 && val.length == 3)
return false;
if(val.indexOf('.') == 0)
val = '0' + val;
if(e.which != 46)
{
strval = val + String.fromCharCode(x);
var re = /^((.|0|[1-9]\d?)(\.\d{1})?|100(\.0?)?)$/;
if(!re.test(strval))
return false;
}
}
else if(val.indexOf('.') > 0)
{
if(e.which == 46 )
return false;
var arra = val.split('.');
var decval = arra[1];
var val = arra[0];
if(val.length > 6)
return false;
if(decval.length > 0)
return false;
}
else if(e.which != 46 )
{
if(val.length > 5)
return false;
}
}
Use following regex
^\d{0,4}([.\d]\d)?$
Regex explanation here
If you don't want to match 5 digits then use negative look-ahead assertion to avoid that
^(?!\d{5}$)\d{0,4}([.\d]\d)?$
Regex explanation here
/^(?:\d{0,4}\.?(\d)|\d{0,6})?$/
NOTE: This also matches .2 and 12345 and '' (empty string). Based on your question, its not clear if you want to exclude those.
Explanation:
^ Start the line.
(?: Start a "non-capturing group".
\d{0,4} Between 0 and four digits.
\.? Zero or one literal dots.
(\d) Capture one digit. (Do you want this captured?)
| OR
\d{0,6} Zero or Six digits.
) Closes our non-capturing group (number 2).
$ End the line.
Tests:
var reg_exp = /^(?:\d{0,4}\.?(\d)|\d{0,6})?$/;
[
'1.2',
'113.5',
'1234.5',
'456789',
'12345',
'.2',
'',
'1234.',
'113.55'
].forEach(c => {
console.log('"' + c + '" tests to "' + reg_exp.test(c) + '"');
});
// "1.2" tests to "true"
// "113.5" tests to "true"
// "1234.5" tests to "true"
// "456789" tests to "true"
// "12345" tests to "true"
// ".2" tests to "true"
// "" tests to "true"
// "1234." tests to "false"
// "113.55" tests to "false"

Can only type numbers 9 < 37 only

How can I make an input type only numbers, and only numbers less than 36 and greater than 9 available? Can you do this in JavaScript?
I have this to only let numbers allowed in an input:
function isNumber(evt) {
evt = (evt) ? evt : window.event;
var charCode = (evt.which) ? evt.which : evt.keyCode;
if (charCode > 31 && (charCode < 48 || charCode > 57)) {
return false;
}
return true;
}
Yeah, this can be done. Just use isNaN() (is not a number). So what you want is basically
if(!isNaN(number) && (number > 9 && number < 36)){
//do stuff
} else {
//do something else like alert user that they need to enter a number between 10 and 35
}
Just to be clear, you'd be using ! so that !isNaN(10) will return true since isNaN(10) would come back as false, so we need to make it a truthy value.
Edit: I'm guessing you're new to this, so I'm going to adhere to your request and help you out a bit:
if (!isNaN(number) && (number > 9 && number < 36)) {
//do stuff
} else if (isNaN(number)) {
alert('Please enter a number');
} else if (number <= 9 || number >= 36) {
alert('Please enter a number between 10 and 35');
}
Take this as a learning experience. Follow the logic. Break your problem into smaller problems.

javascript to allow only negative and positive numbers and decimal upto 6 digits on keypress

I need to validate a textbox in my cshtml page to accept only negative or positive numbers and upto 6 decimal places. This is what I have tried so far.
function AcceptUptoSixDecimalPlacesWithNegative(event, elem) {
if ((event.which != 46 || $(elem).val().indexOf('.') != -1) && (event.which < 48 || event.which > 57)) {
if (event.keyCode !== 8 && event.keyCode !== 46 && event.keyCode !== 9 && event.keyCode !== 0 && event.keyCode !== 45) { //exception
event.preventDefault();
}
}
var text = $(elem).val();
if ((text.indexOf('.') != -1) && (text.substring(text.indexOf('.')).length > 6)) {
if (event.keyCode !== 8 && event.keyCode !== 46 && event.keyCode !== 9) { //exception
event.preventDefault();
}
}
This is helping me achieve six digits after decimal point but then it allows all special characters and alphabets too.
Any help with this problem would be appreciated.
Thanks.
You could check the value with Regex:
var re = /^-?\d*\.?\d{0,6}$/;
var text = $(elem).val();
var isValid = (text.match(re) !== null);
The Regex means:
^ : beginning of string
-? : one or zero "-"
\d* : 0 to infinite numbers
\.? : 0 or 1 "."
\d{0,6} : from 0 to 6 numbers
$ : End of string
You could use the isNaN() function of JavaScript.
var inputPrevValue = "";
$(document).ready(function () {
$("#numbersOnly").change(function () {
if (isNaN($(this).val()) || $(this).val().length > 6) {
$(this).val(inputPrevValue);
} else {
inputPrevValue = $(this).val();
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<input type="text" id="numbersOnly">
This is a (very simplistic) example that tests if the input is a number less than 6 characters in length. If not, it'll revert it to the last acceptable value.
***Adding Comment as no access yet!!!
Try Regex "^[0-9]+(.[0-9]{1,2})?$" to verify the text and then proceed with logic.
js code:
var patt = new RegExp("^[0-9]+(.[0-9]{1,6})?$");
var res = patt.test(str);
if res is true then proceed else return false;
Here are a list of functions to help in your question:
Math.sign() checks if its a positive/0, negative/0 and NaN
Number MDN contains a list of number functions
parseFloat()
count digits after decimal post or regex ie. \d+([.\d{1,6}]*)\
In your context, a combination of validations in the following example:
let x = elem;
if(Math.sign(x) === 1 || Math.sign(x) === -1) && ...
// decimal validations
Hope this helps.
Don't validate the keys pressed. There are many ways to change input
value. Handle the oninput event.
You may treat the value as a string and validate using a
regular expression, but I think it's better to combine string and number-related
functions
For example:
<input type="number" step="any" oninput="validate(this)" />
function validate(input){
var number = parseFloat(input.value);
if( number == input.value && input.value.length <= number.toFixed(6).length ){ /* valid! */ }
}
http://jsfiddle.net/tto2yvwj/

Javascript validation - Min/Max number of characters AND must contain number

I have the following problem:
I need to validate an input (password field) with Javascript / jQuery
The rules are:
it must be 8 to 32 characters
it must contain letters AND at least one number
So my logic is the following but I can't seem to be able to implement it
be 8 to 32
if it's NOT 8 to 32 characters and doesn't have numbers
{
jQuery('#passwordfield').addClass('error');
}
I tried the following (just with 0 as number, for test purposes)
if(((jQuery('#passwordfield').val().length <= 7) || (jQuery('#passwordfield').val().length >= 33)) && ((jQuery('#passwordfield').val().indexOf("0") == -1)))
{
jQuery('#passwordfield').addClass('error');
}
The problem with the above code is that it returns true if you type enough characters (8 to 32) and NOT contain a number since the first part of the && is true
Try this :
var p = jQuery('#passwordfield').val();
if(p.length <=7 || p.length >= 33 || !p.match(/\d/) || !p.match(/[a-z]/i))
$('.whatever').addClass('error');
You can use regular expression:-
var val = jQuery('#passwordfield').val();
if(val.length <=7 || val.length >= 33 || !/[0-9]/.test(val) || !/[a-zA-Z]/.test(val))
{
// show error
}
String must contain 0..* letters and 1..* numbers (with a total length of 8..32):
if (str.search(/^[a-zA-Z0-9]{8,32}$/) == -1 || str.search(/\d/) == -1) {
jQuery('#passwordfield').addClass('error');
}
String must contain 1..* letters and 1..* numbers (with a total length of 8..32):
if (str.search(/^[a-zA-Z0-9]{8,32}$/) == -1 || str.search(/[a-zA-Z]\d|\d[a-zA-Z]/) == -1) {
jQuery('#passwordfield').addClass('error');
}

jQuery function for check textbox

I’d like use jquery function that validate a input field. This input field must be used for entering 11 digit numbers that start with 0.
I tried some function but doesn’t work!
function check(mob) {
var firstnum = mob.substring(1);
alert(firstnum);
if (firstnum != "0" || mob.lenght != 11)
return false;
else
return true;
}
function check(mob) {
return mob.substring(0, 1) == '0' && mob.length == 11;
}
String Method Reference
If you want to check is it 11 digit, you should use RegExp
function check(mob) {
return mob.match(/^0\d{10}$/) != null;
}
You need to use .charAt(0) to get the first character of a string. .substring(1) will return the rest of the string minus the first character.
"01234567890".substring(1) = "1234567890"
"01234567890".charAt(0) = "0"
"01234567890".length = 11 (assuming that you have spelled "length" correctly in your code)
Edit: Since you also need to check for digits, you could use a regular expression to verify this (although the whole check could also be done with a regex)
The completed function could therefore be simplified to just:
function isValidMobile(mobileNumber) {
return mobileNumber.charAt(0) == 0 && mobileNumber.length === 11 && /^\d+$/.test(mobileNumber);
}
Or without the regex
function isValidMobile(mobileNumber) {
return mobileNumber.charAt(0) == 0 && mobileNumber.length === 11 && !isNaN(mobileNumber);
}
if (firstnum >= 1 || mob.lenght <= 11) //lenght spell wrong
change to
if (firstnum >= 1 || mob.length<= 11)
you can give it a try
function check(mob) {
var num = parseInt(mob);
if (mob+'' == '0'+num && mob.length == 11)
return true;
else
return false;
}
here what I am doing is that parseInt will give you exact same number without 0 if all characters are numbers, so in the condition I am just adding 0 in starting and checking with mobile number , it will do 2 validation in once , all are number starts with 0 and next validation is for length
Try using a simple regex as below
function check(mob) {
return /^0\d{10}$/.test(mob)
}
function check(mob) {
if(!isNaN(mob)){ // or use parseInt
var firstnum = mob.charAt(0);
alert(firstnum);
if (firstnum != "0" || mob.length != 11) {
return false;
} else {
return true;
}
}
}

Categories

Resources