Trying to validate if the user has entered a name starting with a letter, is at least 8 characters long, and has at least one number in it. See the code below:-
The first two conditions I have been able to make work, its validating whether or not there's a number within. I have tried to run a function all by itself with just the number validation in it but I cant seem to get it to work. this is my latest attempt to make it work, any help would be greatly appreciated, keep in mind I am a first year student :)
function nameVerify() {
var char1;
var char2;
var index;
var NL = "\n";
var valid = false;
char1 = useNam.substr(0, 1);
char1 = char1.toUpperCase();
char2 = useNam.substr(1);
for (index = 1; index <=useNam.length; index++){
while (!valid) {
if ((char1 <"A" || char1 >"Z") || (useNam.length <8) && (char2 >=0 || char2 <=9)){
alert("alert 1");
useNam = prompt("prompt 2");
char1 = useNam.substr(0, 1);
char1 = char1.toUpperCase();
char2 = useNam.substr(1);
}
else {
valid = true;
alert("Congragulations, you entered it correctly");
}
}
}}
var useNam;
useNam = prompt("prompt 1");
result = nameVerify(useNam);
/**
* #param {string} str name to test
* #return {boolean} true if str is valid
*/
function isValidName(str) {
return /^[a-zA-Z][a-zA-Z0-9]{7,}$/.test(str) && /\d/.test(str)
}
/^[a-zA-Z][a-zA-Z0-9]{7,}$/ tests that it starts with a letter, is at least 8 characters long, and all characters are letters or numbers. /\d/ tests that it contains at least 1 number. See MDN's RegExp documentation for reference in particular about the special characters and the x{n,} syntax described there. If you allow underscores too then you could use /^[a-zA-Z]\w{7,}$/ for the first test.
Try this
valid = myString.match(/\d/).length > 0
This is a regex and will return the first number it matches or an empty array otherwise
Related
I have created a JS fiddle https://jsfiddle.net/95r110s9/#&togetherjs=Emdw6ORNpc
HTML
<input id="landlordstreetaddress2" class="landlordinputs" onfocusout="validateinputentries()" />
JS
validateinputentries(){
landlordstreetaddress2 = document.getElementById('landlordstreetaddress2').value;
goodcharacters = "/^[a-zA-Z0-9#.,;:'\s]+$/gi";
for (var i = 0; i < landlordstreetaddress2.length; i++){
if (goodcharacters.indexOf(landlordstreetaddress2.charAt(i)) != -1){
console.log('Character is valid');
}
}
}
Its pulling the value from an input and running an indexOf regex expression with A-Z a-z and 0-9 with a few additional characters as well.
The problem is that it works with the entry of BCDEFG...etc and 12345...etc, but when I type "A" or "Z" or "0" or "1", it returns incorrectly.
I need it to return the same with 0123456789, ABCDEF...XYZ and abcdef...xyz
I should point out that the below does work as intended:
var badcharacters = "*|,\":<>[]`\';#?=+/\\";
badcharacter = false;
//firstname
for (var i = 0; i < landlordfirstname.value.length; i++){
if (badcharacters.indexOf(landlordfirstname.value.charAt(i)) != -1){
badcharacter = true;
break;
}
if(landlordfirstname.value.charAt(0) == " "){
badcharacter = true;
break;
}
}
String.prototype.indexOf()
The indexOf() method returns the index within the calling String object of the first occurrence of the specified value, starting the search at fromIndex. Returns -1 if the value is not found.
So, you're trying to search this value "/^[a-zA-Z0-9#.,;:'\s]+$/gi" which "never" will be found in the entered string.
You actually want to test that regexp against the entered value.
/^[a-zA-Z0-9#.,;:'\s]+$/gi.test(landlordstreetaddress2)
function validateinputentries() {
var landlordstreetaddress2 = document.getElementById('landlordstreetaddress2').value;
if (/^[a-zA-Z0-9#.,;:'\s]+$/gi.test(landlordstreetaddress2)) {
console.log('Characters are valid');
} else {
console.log('Characters are invalid');
}
}
<input id="landlordstreetaddress2" class="landlordinputs" onfocusout="validateinputentries()" />
You're trying to combine two different methods of testing a string -- one way is with a regex; the other way is by checking each character against a list of allowed characters. What you've wound up with is checking each character against a list of what would have been a regex, if you hadn't declared it as a string.
Those methods conflict with each other; you need to pick one or the other.
Check each character:
This is closest to what you were attempting. You can't use character ranges here (like a-zA-Z) as you would in a regex; you have to spell out each allowed character individually:
var validateinputentries = function() {
var address = document.getElementById('landlordstreetaddress2').value;
var goodcharacters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789#.,;:' ";
var badcharactersfound = false;
for (var i = 0; i < address.length; i++) {
if (goodcharacters.indexOf(address.charAt(i)) == -1) {
badcharactersfound = true;
console.log("not allowed: ", address.charAt(i));
}
}
if (badcharactersfound) {
// Show validation error here
}
}
<input id="landlordstreetaddress2" class="landlordinputs" onfocusout="validateinputentries()" />
Regular Expressions
The regex version is much simpler, because the regular expression is doing most of the work. You don't need to step through the string, just test the whole string against the regex and see what comes out. In this case you're looking to see if the input contains any characters that aren't allowed, so you want to use the character exception rule: [^abc] will match any character that is not a, b, or c. You don't want to anchor the match to the beginning or the end of the string, as you were doing with the initial ^ and the trailing $; and you can leave out the + because you don't care if there are sequential bad characters, you just care if they exist at all.
var validateinputentries = function() {
var address = document.getElementById('landlordstreetaddress2').value;
var regex = new RegExp("[^a-zA-Z0-9#.,;:'\\s]","g")
var badcharactersfound = address.match(regex);
// or the above two lines could also have been written like this:
// var bad = address.match(/[^a-zA-Z0-9#.,;:'\s]/g)
// In either case the "g" operator could be omitted; then it would only return the first bad character.
if (badcharactersfound) {
console.log("Not allowed: ", badcharactersfound);
}
}
<input id="landlordstreetaddress2" class="landlordinputs" onfocusout="validateinputentries()" />
I'm trying to solve a password checker challenge and I've got to a stage where 1 string is matching for two expressions.
Rules:
return 'too short' for any string that is less than 6 characters
return 'okay' if the string is less than 12 characters, features one or more underscores, or a number, or with a mix of uppercase/lowercase letters
var str = 'aBB33'
var lessthansixRegex = new RegExp(/^(?=.*?[a-z])(?=.*?[A-Z])|(?=.*?\d{1}){0,6}$/);
var okayRegex = new RegExp(/(?=.*?[a-z])(?=.*?[A-Z])|(?=.*?\d{1})|(?=.*?[_]{1})/);
if (okayRegex.test(str) && str.length < 12) {
return 'okay';
} else if (tooshortRegex.test(str) && str.length < 6) {
return 'too short';
}
Is there a way to check this or are the paramaters of the challenge messed up.
One solution you might easily spot is the lack of '' however the 'okay' regex must have that parameter as an or '|' because there are other strings than need to match it that also don't include ''.
Feel free to let me know if you spot any other bugs.
Thanks a lot!
I think you've overcomplicated things here, why not just check the string lengths rather than write a regex for it? Also I think your regex could be simpler:
var str = 'aBB33';
var okayRegex = /[_\d]|[A-Z]+.*[a-z]+|[a-z]+.*[A-Z]+/;
if (str.length < 6 || str.length > 11) {
return 'password must be between 6 & 11 characters';
} else if (okayRegex.test(str)) {
return 'ok';
} else {
return 'invalid password';
}
Seeing as this is about the regex let me explain what's happening:
[_\d] // match any underscore or digit (number)
| // or (checks whether what's before or after is true)
[A-Z]+.*[a-z]+ // check for at least one A-Z followed by any gap
// of characters followed by at least one a-z
| // or
[a-z]+.*[A-Z]+ // reverse of last check (lower then upper)
Hope that helps!
Your regex seems too complicated. You can reach your solution by testing against each individual regex and provide a specific error message based on each condition by doing something like this
var containsNumber = new RegExp('\d');
var containsUnderscore = new RegExp('[_]');
var containsUpperCase = new RegExp('[A-Z]');
var containslowerCase = new RegExp('[a-z]');
if (str.length < 6 || str.length > 11) {
return 'password must be between 6 & 11 characters';
} else if (!containsNumber.test(str)) {
return 'password must contain a number';
}else if (!containsUnderscore.test(str)) {
return 'password must contain underscore';
}else if (!containsUpperCase.test(str)) {
return 'password must contain upper case character';
}else if (!containslowerCase.test(str)) {
return 'password must contain lower case character';
}
I am trying to restrict the user somewhat regarding the username they can use, based on length and context.
Here, I am trying to make my username label red when a forbidden word is found when the user leaves the current textbox.
Although the code looks just fine to me, it seems like it completely ignores the forbidden words and makes the label green anyway if the other criteria a met. What is wrong with my code?
var username = document.forms.LogInForm.username;
username.onblur = function() {
var forbiddenWords = ["fff, dddd, aaa, rrrr, oooo"];
var regex;
var username_value = this.value.split('');
for (var a = 0; a < forbiddenWords.length; a++) {
regex = new RegExp('\\b' + forbiddenWords[a] + '\\b');
if (username_value[username_value.length - 1] === "-" || username_value[username_value.length - 1] === "_") {
console.log('Username cannot end in dash (-) or underscore (_). We removed it for you!');
this.value = this.value.slice(0, -1);
}
else if (this.value.length < 4) {
console.log('Username cannot be less than 4 characters');
document.getElementById('username_label').style.color = "red";
}
else if (username.value.search(regex) >= 0) {
console.log('Username contains swearing word. Please, remove it');
document.getElementById('username_label').style.color = "red";
}
else {
document.getElementById('username_label').style.color = "green";
}
}
};
var forbiddenWords = ["fff, dddd, aaa, rrrr, oooo"];
is most likely a mistake and should read
var forbiddenWords = ["fff", "dddd", "aaa", "rrrr", "oooo"];
You want an array of separate strings, not a one element array containing string which has some commas and spaces as content.
I probably wouldn't use \b. If you use \b the user could just type a swear word then add any character and the regex will not find anything.
Also, if the last forbidden word is not found validation color shows as passed because of your else statement. You should have a separate loop for forbidden words only, and mark a value as valid or invalid and display colors based on that.
I am a new to JavaScript. I have tried to use regular expression in ifcondition.
Here is my code:
var location1 = 3;
var location2 = 4;
var location3 = 5;
var guess;
var hits = 0;
var guesses = 0;
var string = "";
var reg = /[0-6]/i;
var isSunk = false;
while (isSunk == false) {
guess = prompt("Ready, aim, fire! (enter a number 0-6): ");
if (guess != reg || guess ==string) {
alert("Please enter a valid cell number!");
} else {
guesses = guesses + 1;
if (guess == location1 || guess == location2 || guess == location3) {
hits = hits + 1;
alert("HIT!");
if (hits == 3) {
isSunk = true;
alert("You sank my battleship!");
}
} else {
alert("MISS!");
}
}
}
var stats = "You took " + guesses + " guesses to sink the battleship, " + "which means your shooting accuracy was " + (3 / guesses);
alert(stats);`
My problem is in this if (guess != reg || guess ==string) condition. It didn't work as I expected. I would like that function prompt allows only 0,1,2,3,4,5,6 numbers without any words and spaces. But in fact If I enter one of needed number (1 for example) it won't allow to execute further actions. I read a lot through stackoverflow about regular expression in Javascript (Convert the Regular expression, Regular expression, Basic regular expression) and more but I could not find the answer to my problem.
So the question is:
How to set proper regular expression in if condition in JavaScript if it has already declared as variable?
To test whether a string matches a regular expression you can't just compare them using the standard comparison operators. Something that should work is
if (reg.test(guess)) {
....
}
Also the regular expression [0-6]i also matches the string "hello1, since there is a one in it. What you want is probably something like ^[0-6]$. The test for the empty string is also unnecessary, by the way, since "" does not match that expression.
To explain: The ^ and the $ match the beginning and the end of the string, respectively. Framing a regular expression with these symbols essentially says that the whole string, not only a substring, has to match the expression.
Regular expression are not the right tool here.
guess = prompt("Ready, aim, fire! (enter a number 0-6): ");
guess = +guess; // Convert *guess* to number, sets to NaN if not numeric
if (guess >= 0 && guess <= 6) { // check if number is in range (NaN will fail)
....
Here's what I tried...
It works if I only check if the value of the input is lesser than 8, but doesn't work to check if it contains at least 1 letter and 1 digit. What am I doing wrong ? =/
$(document).ready(function() {
var jVal = {
'passWord' : function() {
$('body').append('<div id="nameInfo" class="info"></div>');
var nameInfo = $('#nameInfo');
var ele = $('#password');
var pos = ele.offset();
ra = /^[A-Za-z]+$/;
re = /^[0-9]+$/;
nameInfo.css({
top: pos.top - 3,
left: pos.left + ele.width() + 15
});
if (ele.val().length < 8 & re.test(ele.value) & ra.test(ele.value)) {
jVal.errors = true;
nameInfo.removeClass('correct').addClass('error').html('← too short').show();
ele.removeClass('normal').addClass('wrong');
}
else {
nameInfo.removeClass('error').addClass('correct').html('√').show();
ele.removeClass('wrong').addClass('normal');
}
}
}
$('#password').change(jVal.passWord);
});
ra checks if the password is made ENTIRELY of letters. re checks if the password is made ENTIRELY of numbers. They are mutually exclusive and therefore cannot both be true.
Instead, use ra = /[a-z]/i; re = /[0-9]/;.
EDIT: Also, since you're using jQuery, you should be testing on ele.val(), not ele.value.
You could use a single regex to do everything:
/^(?=.*\d.*)(?=.*[a-z].*)\w{8,}$/i
The first two pieces check for both a digit, and an a-z char in the whole string, and then the last piece ensures it's at least 8 characters. You could change the last \w to . to allow special chars if so desired.