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

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

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"

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 password validation using regex

I have a problem with my password validation using regex on javascript. the criteria are :
have at least one or more letter(it can be upper case or lower case)
have at least one or more number
character length minimal 3 and maximal 30
I hope anyone can help me to solve this problem :)
var ch_pass = /^([0-9]+).([a-zA-Z]+).({3,30})$/;
You can use lookahead like this:
var ch_pass = /^(?=.*?[0-9])(?=.*?[a-zA-Z]).{3,30}$/;
I wouldn't recommend trying to do this whole check in a single regular expression because it just over complicates it. Do each condition individually.
Has at least one letter:
var has_letters = (/[a-zA-Z]/).test(password);
Has at least one number:
var has_numbers = (/[0-9]/).test(password);
Has between 3 and 30 characters (inclusive):
var has_length = 3 <= password.length && password.length <= 30;
This can all be wrapped up into a function:
function is_password_valid(password) {
var has_letters = (/[a-zA-Z]/).test(password);
var has_numbers = (/[0-9]/).test(password);
var has_length = 3 <= password.length && password.length <= 30;
return has_letters && has_numbers && has_length;
}
Or if you prefer something more dense:
function is_password_valid(password) {
return ((/[a-zA-Z]/).test(password)
&& (/[0-9]/).test(password)
&& password.length >= 3
&& password.length <= 30);
}

jQuery: Check if special characters exists in string

I know this question is asked more often here on Stack, but I can't seem to get a straight answer out of the questions already posted.
I need to check if all special characters (except -) are in a string, if so, then give the user an alert.
What I have so far is this:
if($('#Search').val().indexOf('#') == -1 || $('#Search').val().indexOf('#') == -1 || $('#Search').val().indexOf('$') == -1 || $('#Search').val().indexOf('%') == -1 || $('#Search').val().indexOf('^') == -1 || $('#Search').val().indexOf('&') == -1 || $('#Search').val().indexOf('*') == -1 || $('#Search').val().indexOf('(') == -1 || $('#Search').val().indexOf(')') == -1 || $('#Search').val().indexOf('_') == -1 || $('#Search').val().indexOf('\'') == -1 || $('#Search').val().indexOf('\"') == -1 || $('#Search').val().indexOf('\\') == -1 || $('#Search').val().indexOf('|') == -1 || $('#Search').val().indexOf('?') == -1 || $('#Search').val().indexOf('/') == -1 || $('#Search').val().indexOf(':') == -1 || $('#Search').val().indexOf(';') == -1 || $('#Search').val().indexOf('!') == -1 || $('#Search').val().indexOf('~') == -1 || $('#Search').val().indexOf('`') == -1 || $('#Search').val().indexOf(',') == -1 || $('#Search').val().indexOf('.') == -1 || $('#Search').val().indexOf('<') == -1 || $('#Search').val().indexOf('>') == -1 || $('#Search').val().indexOf('{') == -1 || $('#Search').val().indexOf('}') == -1 || $('#Search').val().indexOf('[') == -1 || $('#Search').val().indexOf(']') == -1 || $('#Search').val().indexOf('+') == -1 || $('#Search').val().indexOf('=') == -1)
{
// Code that needs to execute when none of the above is in the string
}
else
{
alert('Your search string contains illegal characters.');
}
But this doesn't seem to work. Can anyone help me on this matter?
If you really want to check for all those special characters, it's easier to use a regular expression:
var str = $('#Search').val();
if(/^[a-zA-Z0-9- ]*$/.test(str) == false) {
alert('Your search string contains illegal characters.');
}
The above will only allow strings consisting entirely of characters on the ranges a-z, A-Z, 0-9, plus the hyphen an space characters. A string containing any other character will cause the alert.
var specialChars = "<>#!#$%^&*()_+[]{}?:;|'\"\\,./~`-="
var check = function(string){
for(i = 0; i < specialChars.length;i++){
if(string.indexOf(specialChars[i]) > -1){
return true
}
}
return false;
}
if(check($('#Search').val()) == false){
// Code that needs to execute when none of the above is in the string
}else{
alert('Your search string contains illegal characters.');
}
You could also use the whitelist method -
var str = $('#Search').val();
var regex = /[^\w\s]/gi;
if(regex.test(str) == true) {
alert('Your search string contains illegal characters.');
}
The regex in this example is digits, word characters, underscores (\w) and whitespace (\s). The caret (^) indicates that we are to look for everything that is not in our regex, so look for things that are not word characters, underscores, digits and whitespace.
You are checking whether the string contains all illegal characters. Change the ||s to &&s.

regex for javascript pattern match

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

Categories

Resources