check if an input is of this form - javascript

I have a code where the user enters multiple strings and I store them in an array, then I want to check if all the inputs are valid.
An input valid is a number with the same character repeated 3 times.
For example : '333', '999', '222', ...
What I have tried :
let valid = true;
inputs.forEach((input) => {
if (input.length !== 3 || isNaN(input)) {
valid = false;
} else {
const first = input[0];
for (let i = 1; i < 3; i++) {
console.log(first,input[i])
if (input[i] !== first) {
valid = false;
}
}
}
});
console.log(valid);
this code is working and I want to know if can I do better it seems like I used too much code for this simple task and I want to know if there is a simpler code when I searched in the interned they suggest rejex but this is so complicated for me thank you for helping me

First of all for a beginner your solution is good and correct congrats however you can optimize it and make it simpler
you can use every instead of forEach there is no need to check all the inputs once you find an invalid one
instead of loop through the input you can check if it is not divisible by 111 ;)
if(parseInt(input) % 111 !== 0) valid = false;

You could use Array#every.
let valid = inputs.every(s => s.length === 3 && !isNaN(s)
&& [...s].every(c => c === s[0]));
This could be shortened with a regular expression:
let valid = inputs.every(s => /^(\d)\1{2}$/.test(s));

Related

Javascript validate password field input

i want to validate a password field with the following conditions:
One uppercase character
One lowercase character
One number
One special character
Eight characters minimum
If the password input is correct i want to make the pass field green if not it should be red.
I tried with this code but doesnt work:
let password = document.querySelectorAll(".control-group")[3];
password.addEventListener("focusout", () => {
let inp = password.value;
if (
inp.match(/[a-z]/g) &&
inp.match(/[A-Z]/g) &&
inp.match(/[0-9]/g) &&
inp.match(/[^a-zA-Z\d]/g) &&
inp.length >= 8
) {
password.style.backgroundColor = "green";
} else {
password.style.backgroundColor = "red";
}
});
The code you provided is not working due to the fact that
inp.match(/[a-z]/g) && inp.match(/[^a-zA-Z\d]/g)
is just "false". You are telling there "if it contains alphabetic characters as well as it doesn't contains any", which is some sort of
let i = 0;
if (i == 1) {...}
As I said on one of the comments of your question, just search for another solution, like the one that #harsh-saini said.
Output of match() is not true or false, but the match thing like str or int or if it wrong it will show null. So in your case better use "if your case (if input.match() != null) as true". There is the example !
var input = "GoodMorning Sir"
if (input.match(/[0-9]/g) != null){
console.log("there are number here")
} else if (input.match(/[A-Z]/g) != null){
console.log("there are uppercase here")
}
//this is your if else code, try to console.log your condition
//as you can see it wont giving output true or false
console.log(input.match(/[A-Z]/g)) // ["G", "M" , "S"]

How can I create a loop for a prompt, when the answer is unacceptable for a criteria?

so I've been working on a password generator and I have it working aside from 2 things. The password must be within 8-128 characters long. I have a prompt that asks the user how long they would like the password to be and then a few other prompts about including symbols, uppercase, lowercase, and numbers. However, when the user answers with anything bellow 8 or above 128 I would like an alert to say "password must be at least 8 characters long and shorter than 128" then loop back to the prompt asking them again how long they would like the password to be.
I can not for the life of me figure out how to do this. the obvious solution to me was a while loop however I am not experienced in building those.
I also want a minimum of one character type selected before the "confirm" system ends and to loop back to the beginning of the confirms for upper, lower, symbols, and numbers so the user has to pick at least one.
any help would be greatly appreciated.
thank you!
here is the code for the password length
var passLength;
while (passLength >= 129 || passLength <= 7) {
passLength = parseInt(prompt('How many charcters would you like? (8-128)'))
if (passLength <= 128 || passLength >= 8) {
break;
}
alert("Password length must be 8 to 128 characters long!");
}
here is the code for the separate characters that I need at least one of to be selected.
var chosenCharactersArr = []
var passwordstring = ''
if (confirm('would you like Capital letters?')) {
chosenCharactersArr.push(upperCase)
}
if (confirm('would you like to include lowercase letters?')) {
chosenCharactersArr.push(lowerCase)
}
if (confirm('would you like to include numbers?')) {
chosenCharactersArr.push(numbers)
}
if (confirm('would you like to include symbols?')) {
chosenCharactersArr.push(symbols)
}
You have an error with your length check. You cannot use || in this case because you want to check for the lower- and upper limit to be both valid, therefore &&.
For the question cycle, you can use a while (true) loop that you can break once you are done with the questions i.e. config in your case.
I use an object to store the config values with defaults. You could also use an array. However, you have to manage the indices somehow.
const TYPE_NUMBER = 0;
const TYPE_BOOLEAN = 1;
const TYPE_STRING = 2;
const config = {
len: 8,
upc: false,
loc: false,
num: false,
sym: false
};
while (true) {
const len = ask('How many charcters would you like? (8-128)', TYPE_NUMBER);
if (len <= 128 && len >= 8) {
config.len = len; break;
} else {
alert("Password must be 8 to 128 characters long!");
}
}
const upc = ask('Would you like to use capital letters?', TYPE_BOOLEAN);
if (upc) { config.upc = upc; }
// ... repeat the same for the other questions ...
console.log(config);
function ask(msg, type) {
let result;
if (type === TYPE_BOOLEAN) {
result = confirm(msg);
} else if (type === TYPE_NUMBER) {
result = parseInt(prompt(msg));
} else if (type === TYPE_STRING) {
result = prompt(msg);
} else {
result = "";
}
return result;
}

My code should be detecting if a string has currency symbols, but it will not detect £

My code is supposed to detect currency symbols, and execute code based on the result, but the code will not detect the '£' under any circumstances. Here is the relevant code:
let requirements = [ "£", "$" ];
let mcontent = "$£50";
let y = 0;
for (let p = 0; p < requirements.length; ++p) {
if (mcontent.includes(requirements[p])) {
++y;
}
}
if (y == 1) {
//this is considered success, only ONE currency symbol was detected. If mcontent = '$50' or '£50', we should be here.
} else {
//this is considered failure, TWO or ZERO currency symbols were detected. In this scenario, I want the code to fail.
}
I'm aware this may not be the best way to code a function to accomplish what I'm trying to accomplish, so I'm open for better ideas/fixes for what I already have.
The most concise way to do this is to check with RegExp like this:
if (mcontent.match(/£|\$/g)?.length == 1) { // the question mark is so we don't encounter an error if no matches were found
// success
} else {
// failure
}
Here's a live example:
const mcontent1 = '$£50';
const mcontent2 = '£50';
const mcontent3 = '$50';
const regex = /£|\$/g; // slash to escape $ because it has special meaning in regex
console.log(mcontent1.match(regex).length == 1); // false
console.log(mcontent2.match(regex).length == 1); // true
console.log(mcontent3.match(regex).length == 1); // true
If you don't want to use regex, just check if the string includes a symbol, increment a counter, and return whether or not there was exactly 1 match:
let testA = "$£50",
testB = "£50",
testC = "$50";
function checkString(str) {
const symbols = ["£", "$"];
let matches = 0;
for (const symbol of symbols)
if (str.includes(symbol)) matches++;
return matches == 1;
}
console.log(
checkString(testA),
checkString(testB),
checkString(testC)
);
Use RegExp it will return true or flase based on value entred
this example will give you an idea of how to use it
const elementTwo = document.getElementById('elementTwo');
elementTwo.addEventListener("input", function(event) {
pattern = /^[£|$]{1}(\d+)/
if (pattern.test(this.value)) {
console.log("found")
} else console.log("not found")
});
<p>Enter value</p>
<input id="elementTwo" type="text" />

Javascript Form validation with substr

This is part of a javascript to validate a form. This checks to see if it is empty.
if (form.redoarr.value == "") {
alert("Has to be higher");
form.redoarr.focus();
return false;
}
I want to make sure that the 4 digit number entered begins with a 2 digit number under 75. It also has to end in a 2 digit number under 40. How can I use substr to extract the first two digits and make sure they are under 75 and the last two digits and make sure they are under 40. I don't need anything complicated as it's for a single in house user on a private form. I can't just use < 7641 as 1849 is not okay (for instance).
Notwithstanding the usual caveats about never validating a form only in JavaScript (rather than using a server-side language), REGEX is a good fit for this:
let
err,
val = form.redoarr.value
;
if (!val)
err = 'No value entered';
else if (!/^([0-6][0-9]|7[0-4])([0-3][0-9])$/.test(val))
err = 'Value must be four digits, with the first two under 75 and the last two under 40';
if (err) {
form.redoarr.focus();
alert(err);
return false;
}
REGEX is cleaner as you don't need to create any variables. However here's how you'd do it via substring:
let
nums_1 = val.substr(0, 2),
nums_2 = val.substr(2)
;
I hope this solution helps
var value = form.redoarr.value;
var re = /^\d{4}$/;
var error = '';
var first_two_digits = '';
var last_two_digits = '';
if ( !re.test(value) ) {
error = 'Value must be four numbers';
}
first_two_digits = value.substr(0, 2);
last_two_digits = value.substr(2);
if (Number(first_two_digits) >= 75 || Number(last_two_digits) >= 40) {
error = 'Invalid number provided';
}
if (error) {
alert(error);
return false;
}

Check field with at least one or more digits and including characters

I'm making a contact form which will be submitted with jQuery and I'm stuck on one simple validation.
I need to validate a field, which has to have at least x integers.
How can I do this?
p.s: please don't suggest validation plugin.
Thanks,
edit: This is what I've tried, but it's wrong I guess.
var numbercheck = /^(\w\d{7,14})?$/;
this is jsdiffle:
http://jsfiddle.net/4WqY9/
Use regex providing the range of numbers you can afford in your field
like \d{5,10} // Here 5 -10 is the range of numbers
function testContact(contact){
contact = contact.replace(/[a-z]*/g,"");
return (contact == contact.match(/\d{5,10}/))?true:false;
}
To match a number of integers using a regex you'd need something like:
^((\d*)\s*)*$
I'd write a small function that will do the job. Note that this function will return false if you have any non-int elements in the inputText :-
function HasRequiredIntegers(inputText, requiredIntegers) {
var elems = inputText.split(/\s+/);
var intCount = 0;
var nonIntCount = 0;
for (i = 0; i < elems.length; i++) {
if (((parseFloat(elems[i]) == parseInt(elems[i])) && !isNaN(elems[i]))) {
intCount++;
}
else {
nonIntCount++;
}
}
return (intCount >= requiredIntegers && nonIntCount == 0);
}
Try this
function hasUpTo5(strin){
if( string.replace(/[^0-9]/g, '').length <= 5){
return true
}else{
return false;
}
}
alert( hasUpTo5("fhsfbgurb3utn55nun44") );

Categories