Regular expression (For digits and characters) - javascript

I've been experimenting with a local sign in/log in system and I've hit a error. I was trying to make a regular expression that checks if the user's username and password contain 8 characters and 2 numbers. I really am not sure how to do that but this is all my code I've been able too put togheter.
HTML code:
<!DOCTYPE html>
<meta content="text/html;charset=utf-8" http-equiv="Content-Type">
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<form id='form'>
<title>Sign Up #1</title>
<h3>Simple Signup system</h3>
<div>
<label>Username:</label>
<input type="text" name="text1" id = "username">
</div>
<div>
<label>Password:</label>
<input type="text" name="text2" id = "password">
<div>
<button type="button" id="subBtn">Sign Up!</button>
</form>
</body>
<script src="main.js"></script>
</html>
My JS code:
var t = 'everything good, loging in'
var f = 'something is not right, try again.'
var tf = 'not-set'
var statment = /^[a-zA-Z]*$/
window.onload = function() {
document.getElementById('subBtn').addEventListener('click', onSubmit);
}
// main
function onSubmit() {
if (document.getElementById('username').value.includes(Number)) {
tf = 'True'
} else {
tf = 'False'
}
if (document.getElementById('username').value.includes(statment)) {
tf.push('True')
} else {
tf.push('False')
}
if (tf = ['True', 'True']) {
alert('Good to go, redirecting')
} else {
alert('Username does not meet the standards for creating a account!')
}
document.forms['forms1'].submit()
}
EDIT: Was able to redo a part of the code, I'm still using regex to check for letters because I'm not sure how to do it without it.
Current error: 'first can't be a Regular Expression'.

Related

Input box not displaying bigger value on to the users page

I want the programme to get the biggest number that the user has enter in one of the input boxes and display the bigger number to the user.I would also like some improvements to my code. I would it also be possible to do it with one input box instead of two
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
body{
text-align: center;
}
</style>
</head>
<body>
<h1>Max number</h1>
<input id="box1" placeholder="Enter the fist number" type="number">
<input id="box2" placeholder="Enter the second number" type="number">
<button >Submit</button>
<div id="store"></div>
<script>
const box1 = document.getElementById('box1');
const box2 = document.getElementById('box2');
const store = document.getElementById('store');
function max(){
const element = document.createElement('div');
const num1 = box1.value;
const num2 = box2.value;
if (num1<num2 ){
element.innerHTML= num2;
store.appendChild(element);
}
if (num2<num1){
element.innerHTML= num1;
store.appendChild(element);
}
}
</script>
</body>
</html>
First of all, ECMAScript comes with a Math.max() function, so there is no need to re-implement that comparison logic.
Also, your max function doesn’t run automatically. You need to register it as an event listener on the “Submit” button using addEventListener and the click event in order to have it invoked upon clicking the button.
const box1 = document.getElementById('box1');
const box2 = document.getElementById('box2');
const store = document.getElementById('store');
const button = document.getElementById('submit');
// upon clicking on the button …
button.addEventListener('click', () => {
max(); // … run `max()``
});
function max() {
const element = document.createElement('div');
element.innerText = Math.max(box1.value, box2.value);
store.appendChild(element);
}
<h1>Max number</h1>
<input id="box1" placeholder="Enter the fist number" type="number">
<input id="box2" placeholder="Enter the second number" type="number">
<button id="submit">Submit</button>
<div id="store"></div>
Of course, there is not yet a validation that checks if the given values are actually numbers.
I don’t understand your request about doing it with only “one input box”, though, as determining the larger number (out of many) implies having more than one input, so please specify. Do you mean “multiple values in one input box” like comma-separated?
Yes, you can do it all in one input please see the code below
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Get largest number</title>
</head>
<body>
<input type="text" class="myinput" placeholder="Enter your numbers seperated by commas only">
<button class="submit">Get Max</button>
<h1 class="output"></h1>
<script>
const inputElement = document.querySelector('.myinput');
const submitButton = document.querySelector('.submit');
const outputElement = document.querySelector('.output')
submitButton.onclick = function(){
let inputValue = inputElement.value;
if(inputValue !== ''){
try{
let numbers = inputValue.split(',').map(e=>eval(e));
const maxNumber = Math.max(...numbers);
outputElement.innerHTML = 'Largest Number: ' + maxNumber;
}catch(e){
outputElement.innerHTML = 'Incorrect input format!';
}
}
}
</script>
</body>
</html>
The code takes comma separated input from the user and converts it into an array using the split function. Each value separated by the comma will be an array item. I also mapped it to convert the numbers that were in string form to integer form using the eval function. then I used the try catch block to detect any input format errors that may occur that the program will not be able to process and push an error to the user that they have used the incorrect format.
I hope that helps alot!

How to get new input value with each button press?

Upon clicking the button it displays an alert from the input value + a custom string.
My issue is that after clicking the button and changing the input value, clicking the button again displays the old value instead of the new.
Javascript
function test() {
var message = document.getElementById("name").value;
var newMessage = message + " " + "HELLO!";
document.getElementById("send").addEventListener("click", function (e) {
e.stopImmediatePropagation();
alert(newMessage);
console.log(newMessage);
});
}
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="main.js"></script>
<link rel="stylesheet" href="style.css">
<title>Greet your friend</title>
</head>
<body>
<label class="main">Enter the name of your friend you want to greet</label>
<input class="main" type="text" name="name" id="name" value="George">
<button class="main" id="send" onclick=test()>DONE</button>
</body>
</html>
You had uncountable syntax problems which I fixed them. You don't need to use stopImmediatePropagation here.
function test() {
var message = document.getElementById("name").value;
var newMessage = message + " " + "HELLO!";
// -- You don't need a new variable to apply them --
// message += " " + "HELLO!";
// -- Or this one which is better and newer. Called 'String Literals' --
// message = `${message} HELLO!`;
alert(newMessage);
console.log(newMessage);
};
<label class="main">Enter the name of your friend you want to greet</label>
<input class="main" type="text" id="name" />
<button class="main" id="send" onclick="test()">DONE</button>

How to reuse a function without refreshing the page

When i use the function to check if number is positive or negative it works fine but when i try to do it again nothing happens i have to refresh the whole page to make it work again. Any help is welcome!
const userNum = document.querySelector(".user-input").value;
const checkBtn = document.querySelector(".check-input");
const result = document.querySelector(".result");
function checkNum() {
if (userNum > 0) {
result.innerHTML = "Positive!!"
}
else if (userNum < 0) {
result.innerHTML = "Negativeee!!"
}
else if (userNum < 0) {
result.innerHTML = "Number is NULL"
}
else {
result.innerHTML = "Enter a Number!!"
}
return false;
}
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" href="style.css">
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div class="container">
<div class="intro">
<h1>A Program to Check if number is <br></h1>
<h2>Positive, Negative or Null</h2>
</div>
<div class="check-number-type">
<input type="text" class="user-input">
<button onclick="checkNum()" class="check-input">Check</button>
</div>
<div class="show-result">
<p class="result"></p>
</div>
</div>
</body>
<script src="/script.js"></script>
</html>
The reason why you say you have to "reload" the page everytime is because your code that extracts the input value was placed outside of your checkNum function that determines if it's positive or negative.
You only retrieve the input once, when the script starts, instead of getting a fresh copy everytime you enter the checkNum function.
Just move this:
const userNum = document.querySelector(".user-input").value;
Inside the checkNum() function.

Unable to add content using insertAdjacentHTML after i have successfully removed it

this is my code:
"use strict";
const searchBox = document.querySelector("#myText");
const searchBtn = document.querySelector(".btn-search");
const searchContainer = document.querySelector(".search-container");
let mainText = document.querySelector(".main-text");
const quit = document.querySelector("#btn-close");
let showMain;
const newMain = "";
let printMain = function(text) {
showMain = `
<article class="country">
<h1>Country you Searched</h1>
<p>Hello</p>
<p>${text}</p>
</article>`;
console.log(`Our show main is : ${showMain}`);
mainText.insertAdjacentHTML("beforeend", showMain);
};
searchBox.addEventListener("click", function() {
if (searchBox.value === "Type in") {
searchBox.value = "";
}
});
searchBtn.addEventListener("click", function() {
if (searchBox.value && searchBox.value !== "Type in") {
console.log(searchBox.value);
printMain(searchBox.value);
searchBox.value = "";
} else {
alert("please type in country name!");
}
});
quit.addEventListener("click", function() {
//mainText.remove(showMain);
const myDiv = document.getElementById("myId");
const parent = myDiv.parentNode;
parent.removeChild(myDiv);
console.log(showMain);
});
<!DOCTYPE html>
<html lang="en">
<header>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<script defer src="script.js"></script>
<title>Simple Work</title>
<button id="btn-close">go back</button>
</header>
<body>
<main class="container">
<div class="main-text" id="myId"></div>
<p class="search-container">
<label>Type In : </label>
<input type="text" id="myText" value="Type in" />
</p>
<button class="btn-search">input</button>
</main>
</body>
</html>
So, I was trying to make code that add the text using insertAdjacentHTML
and next when I click "go back" button, it will erase the html that I had added using insertAdjacentHTML.
I have success up to this point. After this when I try to add new HTML using insertAdjacentHTML, it doesn't work. What I must do to fix this?
(as my English is second language, explanation might not be clear, I am just making web site that I could add text(must use insertAdjacentHTML) and erase that by using "go back" button and after I erase all of them, it could add new text again by using "input" button)
When you remove the node, you are removing the element that mainText points to, therefore, you code cannot place content into a node that is no longer there. So it throws an error stating so.
You should probably only remove the element with classname of country:
document.querySelector('.country').remove();

how to disable button and show input title

Hi all I have the following code:
my code
let companyNameField = document.getElementById('FormField_6_input');
let button = document.getElementById('ContinueButton_6');
companyNameField.addEventListener('input', validate);
function validate() {
var companyNameValue = companyNameField.value;
var companyRGEX = /[2-9]\d{3}/;
if (companyNameValue.match(companyRGEX)) {
button.disabled = false;
} else {
button.disabled = true;
companyNameField.setAttribute("pattern", '[2-9]\\d{3}');
companyNameField.setAttribute("title", "wrong");
}
}
<form action="" onchange="validate()">
<input type="text" id="FormField_6_input" name="CompanyName" />
<button id="ContinueButton_6">Continue</button>
</form>
With my function, I am checking if my input text satisfies my regex. If not then I disabled my button.
With disabling I also want to set the "title" attribute to my input for showing a message.
With console log I can see that pattern and title were successfully added to my input but when I am starting to write something wrong only my button gets disabled and the title not showing the error message.
How can I fix that?
Actually, title attribute could only be shown while the mouse is hovering on the tag, so it is not suitable to add title in input. Maybe it works in next code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<form action="" onchange="validate()">
<input type="text" id="FormField_6_input" name="CompanyName" />
<button id="ContinueButton_6">Continue</button>
<span id="wrong_text" style="display:none">wrong</span>
</form>
<script>
let companyNameField = document.getElementById('FormField_6_input');
let button = document.getElementById('ContinueButton_6');
let wrongText = document.getElementById('wrong_text');
companyNameField.addEventListener('input', validate);
function validate() {
var companyNameValue = companyNameField.value;
var companyRGEX = /[2-9]\d{3}/;
if (companyNameValue.match(companyRGEX)) {
button.disabled = false;
wrongText.style.display = "inline";
} else {
button.disabled = true;
companyNameField.setAttribute("pattern", '[2-9]\\d{3}');
companyNameField.setAttribute("title", "wrong");
wrongText.style.display = "none";
}
}
</script>
</body>
</html>
Look at the above snippet, I've tried to solve your issue. Let me know if it works
let companyNameField = document.getElementById("FormField_6_input");
let button = document.getElementById("ContinueButton_6");
companyNameField.addEventListener("input", validate);
function validate() {
var companyNameValue = companyNameField.value;
var companyRGEX = /[2-9]\d{3}/;
if (companyNameValue.match(companyRGEX)) {
button.disabled = false;
} else {
button.disabled = true;
companyNameField.setAttribute("pattern", "[2-9]\\d{3}");
companyNameField.setAttribute("title", "wrong");
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>Static Template</title>
</head>
<body>
<form action="">
<input
type="text"
id="FormField_6_input"
name="CompanyName"
onchange="validate()"
/>
<button id="ContinueButton_6" disabled>Continue</button>
</form>
</body>
</html>
instead of using regex you can also use parseInt(); and isNaN(); to only allowing numbers to enter.

Categories