using .trim() with jquery validate plugin - javascript

I am using jQuery Live Form Validation from GeekTantra
The validation is called by ID. Here is the code I use to set the options for a field that is a 2 digit number less than 50:
jQuery("#ValidNumber2Digits50").validate({
expression: "if (VAL.length <= 2 && !isNaN(VAL) && VAL < 50) return true; else return false;",
message: "Please enter a 2 digit number less than 50"
});
The only problem is that it counts white spaces in the length. S0...
_4 ==> good data
4_==> good data
_9_ ==> bad data
_ _2 ==> bad data
I tried:
if (VAL.trim.length <= 2 && !isNaN(VAL) && VAL < 50) return true; else return false;
which did not work.
Any ideas?
Thanks in advance.

trim() is a function - try using $.trim(VAL).length instead.

Related

Validating a password using JavaScript

I'm trying to make a password validation in JS to accept 8-15 digits with at least 1 lower case with this function below, however, it always returns True!
function validatepassword(){
var pass= document.getElementById("pass1").value;
var tester= /^(?=.*[\d])(?=.*[0-9])(?=.*[a-z])[\w]]{8,15}$/;
if (tester.test(pass))
{
document.getElementById("p1prompt").innerHTML=("valid " + "&#10004");
document.getElementById("p1prompt").style.color="green";
return true;
}
else {
document.getElementById("p1prompt").style.color="red";
document.getElementById("p1prompt").innerHTML=("at least 8 digits containing a lower case");
return false;
}
}
EDIT:
Special thanks to Smarx for allowing to use his answer.
function validatepassword(){
var pass= document.getElementById("pass1").value;
if (/[a-z]/.test(pass) && /\d/.test(pass) && pass.length >= 8 && pass.length <= 15)
{
document.getElementById("p1prompt").innerHTML=("valid " + "&#10004");
document.getElementById("p1prompt").style.color="green";
return true;
}
else {
document.getElementById("p1prompt").style.color="red";
document.getElementById("p1prompt").innerHTML=("at least 8 characters containing a lower case");
return false;
}
}
Password : <input type="password" id="pass1">
<p id="p1prompt"></p>
<button onclick='validatepassword()' type="button">Validate</button>
EDIT
I misread the question... I'm actually no longer sure what it's asking for. (The regular expression and the description and the error message in the code all suggest different password requirements.)
The answer below tests for "8-15 characters including at least one digit and at least one lowercase letter."
Although my comment above gives a fix to the regular expression, when you find yourself using a somewhat complicated expression, sometimes it's better to simplify your code by using multiple simpler tests instead. For example:
function isValid(password) {
return /[a-z]/.test(password) && // contains a lowercase letter
/\d/.test(password) && // contains a digit
password.length >= 8 && // at least 8 characters
password.length <= 15; // no more than 15 characters
}
But again, these restrictions are harmful for your users' security. It prevents them from using good, long, random passwords.

Password validation by using java script regular expression contains at least two digit anywhere. It can contain special characters and letters

I need to check for password by using java script regular expression. for the password check, it should have at least two digit, it can contain special character, it has letters as well.
I believe the following script should do the trick. If you're going to use this script, you'll need a button that calls the function with the inputted password as its argument. I hope this helps.
var password;
var passValid = false;
function checkPass(enteredPass) {
if(enteredPass.length >= 2) { //Makes sure that the entered password is equal to or higher than the minimum length
var numsFound = 0;
var letterFound = false;
var splitPass = enteredPass.split("");
for(i=0; i < enteredPass.length; i++) { //Checks all characters for letters and numbers
if(splitPass[i] >= 0 && splitPass[i] <= 9) {
numsFound++;
} else if(splitPass[i] >= "a" && splitPass[i] <= "z" || splitPass[i] >= "A" && splitPass[i] <= "Z") {
letterFound = true;
};
if(numsFound >= 2 && letterFound) { //Successful scenario
password = enteredPass;
console.log("the entered password is valid, updated password successfully");
return;
};
};
};
console.log("the entered password is invalid, update cancelled"); //Error scenario
};
I have framed regular expression, which should check for alphanumeric along with set of special characters and find at least 2 digits.
\(?=(?:[^0-9]*[0-9]){2,})[a-zA-Z0-9!#$*\-.\/?_&,]{1,}\
I took the help of https://regex101.com site for reference & testing.

Number Validation Not Working

I have an input field thats only supposed to take numbers inbetween 1 and 4. If the number is inbetween 1 and 4, it runs some code. If not, it shoots an alert that tells the user to try again with a number between 1 and 4. Here is my code
var number = document.getElementById("num").value;
if(Number(number) === 1 || Number(number) === 2 || Number(number) === 3 || Number(number) === 4 ){
//success code here///
}
else if(Number(number) !== 1 || Number(number) !== 2 || Number(number) !== 3 || Number(number) !== 4) {
} alert("Please type a whole number between(and including) 1 and 4 into the input field.");
I learned that the '.value;' function returns a string, even if the value is a number. So I put the var 'number' in the Number(); function that converts it to a number.
The problem is, when I type 1 into the input field. It shoots the alert even though it equals 1. None of the other numbers work either. I checked the console, and there are no syntax errors(also according to DreamWeaver). Help would be highly appreciated :)
I think you made a simple mistake of putting your alert outside the else if clause.
However there are a few other things you can do to make that a little more readable and efficient.
// Call Number() here so you only have to do it once
var number = Number(document.getElementById("num").value);
// You can also do something like parseInt(document.getElementById("num").value)
// Now check to see if Number() or parseInt() actually parsed an integer out of their input
// and then check that if it's outside your number range
if (isNaN(number) || number < 1 || number > 4) {
alert("Please type a whole number between(and including) 1 and 4 into the input field.");
} else {
// Do Successful code
}
we can write like this also
var patt1 = /[1-4]/g;
if(patt1.test(number)){
//success code here///
}
else{
alert("Please type a whole number between(and including) 1 and 4 into the input field.");
}

JQuery validate regular expression to get interest rate

I want regular expression to get rate of interest. I am wanting to accept following things:
Ex:
0
0.4
0.44
4
44
4.00
44.00
4.2
4.22
44.22
Min 0 and Max 99.99
It must have to accept numeric as well as decimal values but not more than 99.99. Also it should take decimal after first or second digit and after third digit it should display an error message.
I am trying this regular expression but its not perfectly working for me.
$.validator.addMethod('interest', function(value, element) {
return this.optional(element) || /\d{1,2}\.?\d{0,4}/.test(value);
}, 'Please specify a valid data');
Any help would be appreciated.
A regex to match all of those numbers between 0 and 99.99 would be:
^\d{1,2}(\.\d{1,2})?$
so you're pretty close, but your regex matches 0 to 4 digits after the .
EDIT: forgot ^$
Why mess with regexes if you can simply check for the value:
var input = parseFloat(value)
return !isNaN(input) && input >= 0 && input < 100;
If you want to make sure there are at most 2 decimal placed in the string, the check will be a little longer:
return !isNaN(input) &&
input >= 0 &&
input < 100 &&
!(value.split('.')[1] && value.split('.')[1].length > 2);
If you use regex you will end up having two problems. Try:
function validateStuff(input) {
return ($.isNumeric(input) && input >= 0 && input <= 99.99);
}
// Testing:
console.log(validateStuff(5));
console.log(validateStuff("Hello"));
console.log(validateStuff(100));
console.log(validateStuff(99.99));
DEMO

Comparing values with leading zeros in Javascript

I have a javascript code that compares two values:
} else if (!(parseInt($('#form_value').val()) >= 1)){
alert("Error: You didn't pick a number!");
form_value in this case is 001, and I would like to compare it to the one, but it doesn't seem to work. I have tried using parseInt but it didn't work either. Any solutions?
Try:
if (!(Number(parseInt($('#form_value').val(),10)) >= 1)){
EDIT: try this shortened version:
if ( parseInt($('#form_value').val(),10) < 1){
Well, Number("001"); returns 1 and Number("000"); returns 0
based on your comment above
"I'm trying to display an error if the value is less than 1, the
lowest value a user can submit is 000 (which is loaded by default), if
you pick something, it becomes 001."
If the lowest possible value is 0 then just test for 0...
var thing = Number($('#form_Value').val());
if (isNaN(thing) || thing === 0) {
alert('an error message')'
}
May be you should change the condition to if ( +( $('#form_value').val() ) < 1 ) or just if (!+$('#form_value').val()).

Categories

Resources