I have one input field. It may contain either a name or a number.
If the input has at least one letter we handle it as name and its length should be 11 or lower. So valid input might be Bob, 12Bob or Bob23. No empty spaces or other chars are allowed so Bob_1, Bob 23 would be invalid.
If the input contains just digits we handle it as number, if so the number musts start with 00 and should be 16 in length or lower.
Here is my code:
function validateName(){
var name = $('#absender').val();
var length = name.length;
if(/^[a-zA-Z0-9]+$/.test(name)){
if(length > 11){
$('#absender').addClass('error');
$('#bsenderInfo').addClass('error');
disableSave();
return false;
}else{
$('#absender').removeClass('error');
$('#absenderInfo').removeClass('error');
enableSave();
return true;
}
}else if(/^[0-9]+$/.test(name)){
if(name.substring(0,2) != "00"){
$('#absender').addClass('error');
$('#bsenderInfo').addClass('error');
disableSave();
return false;
}
if(length > 17){
$('#absender').addClass('error');
$('#bsenderInfo').addClass('error');
disableSave();
return false;
}else{
$('#absender').removeClass('error');
$('#absenderInfo').removeClass('error');
enableSave();
return true;
}
}else{
$('#absender').addClass('error');
$('#bsenderInfo').addClass('error');
disableSave();
return false;
}
}
Does not matter what the input is, it gives me false if length is 12. Any ideas?
It's because of this line:
if(/^[a-zA-Z0-9]+$/.test(name)){
Every number string fits this regex well, so the "else" statement will be never executed.
You can correct this by checking the number-username case before checking the case [a-zA-Z0-9].
A single regex can handle it:
if (/^(00[0-9]{1,14}|[a-z0-9]{,11})$/i.test(name)) {
// Success condition
...
} else {
// Failure condition
...
}
Related
My exercise is to force a user to type a number and check that it is less than 100. I think I've done this well but there is another case I don't know how to do. If the user does not type any number in the space, the program should show something like "you must type a number". How should I write the code?
var number=prompt('enter a number');
if (number<100){
newnumber=100-number;
document.write(number+'is less than 100 by'+ newnumber);
}else if(number>100){
document.write('type again');
}
You can determine if the users input is a valid number by using the isNaN function. I have also validated the blank character for you, as shown below.
var isValid = !isNaN(number) && number !== "";
Full snippet:
var number = prompt('enter a number');
number = number.replace(/\s/g, "");
var isValid = !isNaN(number) && number !== "";
if (isValid) {
if (number<100) {
newnumber=100-number;
document.write(number+'is less than 100 by'+ newnumber);
} else if(number>100) {
document.write('type again');
}
} else {
document.write("Looks like you didn't enter a valid number");
}
https://jsfiddle.net/ezgn5cv5/
var number = null;
while (number !== 0 && !number || number >= 100) {
number = parseInt(prompt('Enter a number, less than 100'));
}
document.write(
number +
' is less than 100 by ' +
(100 - number)
);
This puts us in a loop for whether or not the number is a valid integer (I assumed that's what you wanted, but you could change this to float or something else), and under 100. Only when the user's input is valid will it go to the line to output.
The second condition for the while loop is !number. This basically tests for falsy conditions, such as NaN or null. If parseInt() can't figure out what the user typed in for a number, it will return NaN. And, of course, we initialized the number variable to null.
The first condition for while is number !== 0 is actually required because of the second condition which tests for falsy. 0 is falsy, but 0 is a valid number less than 100, so we need to make sure that we let 0 be valid. Conditionals like these short circuit. That means that they are processed from left to right, and any condition failing the test will immediately bypass the conditional block of code below. If number is 0, we know that the whole condition is false and we can move on.
The third condition simply ensures we're under 100 by re-prompting if we're not.
Also, I should note that document.write() has some issues. It's better to select an element on the page and set its text.
Remove all spaces .replace(/\s/g, "").
Detect if user input a number using parseFloat() if you want to allow
user to input decimal numbers like 5.254 or only integers using
parseInt() like 5.
Then detect if number > 100 or number < 100.
See this example:
var number = prompt('enter a number');
number = number.replace(/\s/g, ""); //remove all spaces
if (number != "") { // if not empty
if (parseFloat(number) == number) { // if decimal/integer number
if (number < 100) {
newnumber = 100 - number;
document.write(number + ' is less than 100 by ' + newnumber);
} else if (number > 100) {
//number = prompt('enter a number');
document.write('type again');
}
} else {
//number = prompt('enter a number');
document.write('you must type a number');
}
} else { // if empty input
//number = prompt('enter a number');
document.write('shouldn\'t be empty');
}
I am making a login form. Before it submits, I check if all the fields are filled in. I also check if the password is longer than 7 characters and contains at least one number, at least one character, and no spaces. My current code keeps on telling me that I am missing a character no matter what I enter. This is the code:
if($("#password").val()==""){
error += "The password is required.<br>";
}
else if($("#password").val().length<8){
error += "Your password needs at least 8 characters.<br>";
}
else if($("#password").val().length >= 8){
var pass = $("#password").val().split("");
var hasNum = false;
var hasChar = false;
var hasSpace = false;
for(var i = 0; i < pass.length; i++){
if(pass[i] == " "){
hasSpace = true;
}
else if(Number(pass[i]) == NaN){
hasChar = true;
}
else if(Number(pass[i]) != NaN){
hasNum = true;
}
}
if(!hasChar){
error += "Your password must contain at least one character.<br>";
}
if(!hasNum){
error += "Your password must contain at least one number.<br>";
}
if(hasSpace){
error += "Spaces are not allowed in a password.<br>";
}
}
I first check for a space. Then I check if a character can be converted to a number. If not, then it must be a string. If it can be converted, it must be a number. Whatever I type in, it always says "Your password must contain at least one character". How can I fix this? I will give you more code if it is necessary.
The problem is that NaN compares unequal (via ==, !=, ===, and !==) to any other value, including to another NaN value:
NaN === NaN;// false
Number('S') == NaN; //false
Number(10) == NaN; //false
try to use isNaN() instead.
Excuse if this is a stupid question. I'm doing a web design subject at uni and am completely stuck. I have to validate a password using Javascript to ensure it has and uppsercase, lowercase, numerical character, and at least 4 characters.
This is the code I have, it's giving me alerts to say I HAVEN'T included the characters, but when I HAVE included them I'm still getting the alert. Any help appreciated.
var y = document.forms["loginDetails"]["password"].value;
if (y.length < 4) {
alert("Your password needs a minimum of four characters")
}
if (y.search[/a-z/i] < 1) {
alert("Your password needs a lower case letter")
}
if (y.search[/A-Z/i] < 1) {
alert("Your password needs an uppser case letter")
}
if (y.search[/0-9/] < 1) {
alert("Your password needs a number")
return false;
}
Your code had several errors
comparision should be <0 not <1 (search returns negative value when regexp is not found)
/i in regexp (case insensitive - not appropriate when trying to figure out upper/lower case characters)
call of search function was wrong (usage of [] instead of () )
in regexp [] was missing ([] in regexp means one character from given range, so [a-z] will match each lowercase character whereas a-z will match just string 'a-z')
It should look like:
if (y.length < 4) {
alert("Your password needs a minimum of four characters")
} else if (y.search(/[a-z]/) < 0) {
alert("Your password needs a lower case letter")
} else if(y.search(/[A-Z]/) < 0) {
alert("Your password needs an uppser case letter")
} else if (y.search(/[0-9]/) < 0) {
alert("Your password needs a number")
} else {
// Pass is OK
}
There were a few issues with your code:
String.search() returns -1 if the regular expression is not found. Checking against < 1 will still return true incorrectly if the string is found at the 0th (first) character.
String.search() is a function and needs to be called with parentheses ( ) surrounding the arguments, not brackets [ ].
You do not want to perform case-insensitive searches in your regular expressions, so remove the /i option.
Try keeping track of whether or not there was an error in another variable. Then if any of the cases generated an error, you can return false.
Try this:
var error = false;
var message = '';
if (y.length < 4) {
message += "Your password needs a minimum of four characters. ";
error = true;
}
if (y.search(/[a-z]/) == -1) {
message += "Your password needs at least one lower case letter. ";
error = true;
}
if (y.search(/[A-Z]/) == -1) {
message += "Your password needs at least one upper case letter. ";
error = true;
}
if (y.search (/[0-9]/) == -1) {
message += "Your password needs a number.";
error = true;
}
if (error) {
alert(message);
return false;
}
Note that "search" is a function, so you have to call it like y.search(), not with [] brackets (those are used to access a member. y"search" would have the same effect, but search[] is not ok, because it is not an array
Try changing your code this way by:
Adding return false; to each of the failure statement.
Changing the search() function syntax.
You don't need to use /i as it doesn't check the cases.
Code
var y = document.forms["loginDetails"]["password"].value;
if (y.length < 4) {
alert("Your password needs a minimum of four characters")
return false;
}
if (y.search(/[a-z]/) < 1) {
alert("Your password needs a lower case letter")
return false;
}
if (y.search(/[A-Z]/) < 1) {
alert("Your password needs an uppser case letter")
return false;
}
if (y.search(/[0-9]/) < 1) {
alert("Your password needs a number")
return false;
}
the main problem is that you're using the 'i' modifier, what tells the regexp to be case insensitive, try without this modifier.
To improve the user experience I use one error message, so, yo could use this code:
if(/[a-z]+/.test(s) && /[A-Z]+/.test(s) && /\d+/.test(s) && s.length >= 4)
return true;
alert("Your password needs Upper and lower case letters, numbers and a minimum four chars");
return false;
You could try this:
var y = document.forms["loginDetails"]["password"].value;
if (y.length < 4) {
alert("Password should contain minimum four characters");
return false;
}
var pwd=/^(?=.*[a-z])/;
var pwd1=/^(?=.*[A-Z])/;
var pwd2=/^(?=.*[0-9])/;
if (pwd.test(y) == false) {
alert("Password Should contain atleast One lowerCase letter");
return false;
}
if (pwd1.test(y) == false) {
alert("Password Should contain atleast One UpperCase letter");
return false;
}
if (pwd2.test(y) == false) {
alert("Password Should contain atleast One Number");
return false;
}
Or, you could do the same in a single line as well :
var pwd=/^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])/;
if (pwd.test(y) == false) {
alert("Password Should contain atleast One Number, One UpperCase and a lowercase letter");
return false;
}
I am using one If condition in javascript ,
var iid = "c_poqty_"+itemid;
var calculatedQuantity = document.getElementById(iid).value;
if(! isNaN(actualQuantity)) {
if(actualQuantity >= calculatedQuantity) {
return true;
} else {
alert("You must enter the order qty same or greater than the calculated PO Qty");
document.getElementById(iid).focus();
return false;
}
} else {
alert("Please Enter valid number");
document.getElementById(iid).focus();
return false;
}
Here, calculatedQuantity is always in float and while actualQuantity can be integer,
I have one testcase:
calculatedQuantity = 1.0
actualQuantity = 1
Appreciate for your help!
Actually, I suspect they're both strings. Certainly calculatedQty is, as you've retrieved it from the value of an input field, and the value property's value is always a string. Use parseInt and/or parseFloat so you're comparing numbers rather than strings.
Consider:
console.log("1.0" > "1"); // "true"
console.log(1.0 > 1); // "false"
I have this function but I want to check for spaces only in the front and back, not in the middle before i sent back what can i do with it...
function validateNumeric() {
var val = document.getElementById("tbNumber").value;
var validChars = '0123456789.';
for(var i = 0; i < val.length; i++){
if(validChars.indexOf(val.charAt(i)) == -1){
alert('Please enter valid number');
return false;
}
}
return true;
}
Time for regular expressions.
function startsOrEndsWithWhitespace(str)
{
return /^\s|\s$/.test(str);
}
Tests:
> /^\s|\s$/.test('123454')
false
> /^\s|\s$/.test('123 454')
false
> /^\s|\s$/.test(' 123454')
true
> /^\s|\s$/.test(' 123454 ')
true
> /^\s|\s$/.test('123454 ')
true
if i dont wanna accept 1 1 what do i have to change
function containsWhitespace(str)
{
return /\s/.test(str);
}
Tests:
> /\s/.test('123454')
false
> /\s/.test('123 454')
true
> /\s/.test(' 123454')
true
> /\s/.test('123454 ')
true
> /\s/.test(' 123454 ')
true
> /\s/.test(' 123 454 ')
true
For a really simple solution, if you can use jQuery, use jQuery.trim() and compare the trimmed string with the original. If not equal, then there were spaces so the number is invalid.
function trim (myString)
{
return myString.replace(/^\s+/g,'').replace(/\s+$/g,'')
}
source
To trim your string you can write something like this, as it's been said before:
function trim(str){
return str.replace(/^\s+|\s+$/g), '');
}
But why bother?
Want you really want is:
function validateNumeric(str) {
return !isNaN(parseFloat(str));
}
Note your original code accepts something like "..." or "7.8..9" as being numeric, which is wrong.
Update: kennebec has called my attention to the fact that parseFloat() will ignore trailing garbage at the end of string. So I call your attention to this alternative given in an answer to question "Validate numbers in JavaScript - IsNumeric()":
function isNumber(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
(Original credit goes to CMS).
function validateNumeric() {
var val = document.getElementById("tbNumber").value;
if (!/^\s*(?:\d+(?:\.\d*)?|\.\d+)\s*$/.test(val)) {
alert('Please enter a valid number');
return false;
}
return true;
}
(?:\d+(?:\.\d*)|\.\d+) breaks down as follows:
\d+ is any number of digits, e.g. 123
(\.\d*)? optionally matches a fraction, e.g. .25 and . or blank but not .1.2
\.\d+ matches a fraction without an integer part as in .5 but not 1.5.
(?:abc|def) groups things together and matches either abc or def
/^\s*(?:\d+(?:\.\d*)|\.\d+)\s*$/ means any number of spaces followed by one or more decimal digits followed by any number of spaces. So it does what your validChars loop did plus allows spaces at the start and end.