JavaScript simple login from an array - javascript

I have very little experience with JavaScript and can't figure out how to get this to work, it may be a very small fix or it may be something major I have absolutely no clue...
I am trying to just create a really simple login for my assignment, security is not an issue as it is not required in the brief. The event of the user clicking the submit button should either grant or deny the user entry into the site. I have commented throughout the code so hopefully this will be a quick job to spot whatever is going wrong.
It possibly may be the "&" i included in the IF statement, I wasn't entirely sure if it would work in JavaScript or not. Or it may possibly be the calling of the users input, as I am not sure if I did that right either; i.e pass = password (from the form)
JavaScript:
<script>
function loadpage() {
var user = username; //assigns user input to variable
var pass = password; //^^
var storedus = ["Jordan", "Marzia", "Ryan"]; //array of acceptable usernames
var storedps = ["123", "cat", "seven"]; //array of acceptable passwords
if (user = storedus & pass = storedps) //condition must include both an acceptable username and password to >>
{
window.location.href = "home.html"; // >> proceed to next the portal page(home.html)
}
else
{
window.alert("An invalid username or password was entered."); //if the users input was not acceptable then display a popup informing them so.
}
}
</script>
HTML table and form:
<table style="position: absolute; left: 35%; top: 20%;"> <!- table to layout the form to take the users username and password to allow them to
gain entry into the site-!>
<form>
<tr><td><h2>Sign in</h2></td></tr>
<tr><td>Username*: </td><td><input type="username*" name="username" required></td></tr>
<tr><td>Password*: </td><td><input type="password*" name="password" required></td></tr>
<tr><td><input type="submit" name="signin" onclick="loadpage()"</td></tr>
</form>
</table>
Thank you in advance for your help!

You are trying to compare an array with what I'd guess to be a string. Instead, you should loop through the array and compare the values with the username and password.
var usernames = [
'Script47',
'SomeUsernname'
];
var passwords = [
'somePassword',
'password'
];
var username = 'Script47';
var password = 'somePassword'
for (var i = 0; i < usernames.length; i++) {
if (username == usernames[i] && password == passwords[i]) {
alert('Successful!');
break;
} else {
alert('Failed!')
}
}
Notice how I am using &&.
Example
JSFiddle

Related

how can i validate a gmail or yahoo email Address using java script and html

how can I check if an email Address contain gmail or yahoo Address?
i dont need to find if its a real and active one, just to see if the input value recognized thats its gmail or yahoo.
i wrote this code, but its blocking any value on the input and return alert:
const singupVlidation = ()=>{
let email = document.forms['customerinfo']['email'].value;
let gmail = '#gmail.';
let yahoo = '#yahoo.';
if(email.indexOf(gmail) == -1 || email.indexOf(yahoo) == -1 ){
alert('invalid Email address, please correct')
return false;
}
else if(true){
window.location.href="singin.html";
return true;
}
}
heres the html:
<form action="/singup" name="customerinfo" method="post" onsubmit="return singupVlidation()">
<input class="inpt" type="email" name="email" placeholder="Email">
<br>
<input type="submit" value="NEXT" class="submit">
</form>
if i change the code to look only for "#" then its working, what should i change?
The logic of your if is incorrect. You're using || which means OR while you should be using && which means AND.
This is because what you want to do, translated in english is:
If the email doesn't contain #gmail AND the email doesn't contain #yahoo , then give error.
So change your code to
if(email.indexOf(gmail) == -1 && email.indexOf(yahoo) == -1 ){
Furthermore, how you search for #gmail. is not a good method, as you might encounter fake domains like #gmail.myfakedomain.com and you're not considering .ymail.com You could probably be more precise by using a full list of valid domains, e.g. from here and then match the domain exactly instead of doing a string search with indexOf.
e.g.
const singupVlidation = ()=>{
// Define list of valid domains as an array
let domain_list = ['gmail.com', 'googlemail.co.uk', 'ymail.com', 'yahoo.com', 'yahoo.it', '......etc'];
let email = document.forms['customerinfo']['email'].value;
// Extract full domain from the email address
let domain = email.substring(email.lastIndexOf("#") +1);
// Check if the domain is present in the array of valid domains
if (domain_list.includes(domain)) {
window.location.href="singin.html";
return true;
} else {
alert('invalid Email address, please correct')
return false;
}
}

Re-direct homepage according to zip code input

I am trying to create a page where the websites will ask the user to input their zip code. Once the user inputs their zip code website should redirect them to their zip codes homepage. Now I have 10 different zip codes that the user can input. So I created a function for ONE zip code, but now I am stuck, I am not sure if there is a way to input all zip codes in one function or should I create one function per zip code. Thank you for your help.
<script>
function ver(){
var eje=document.getElementById('zip_code').value;
var che=document.getElementById('lugar').value;
var cheje = che.toLowerCase();
if( (eje == 11385 )||(cheje=="ridgewood" ) || (cheje=="glendale") || (cheje=="flushing")){
window.location.assign("c:/users/lui/desktop/fluidimaging.html")
}
else{ alert("you did not enter a city or a zip code"); }
}
</script>
<HTML>
<form>
<legend>Please Enter Your City or Zip Code</legend> <label for ="shippingName">City:
</label> <input type = "text" name = "Name" pattern="[A-Za-z]+" id="lugar" <br/>
<label for = "billingzip">Zip code:</label> <input type = "text" name = "zip" id =
"zip_code" pattern = "[0-9]{5}" required><br/> </form>
<input type = "submit" onclick="ver()" class="submit" value = "Verify"/>
In this case, I would like to suggest that you the following solution.
var zipCodeApps = {
90507: 'https://app.ca.com',
90890: 'https://app.ny.com'
}
This can be obtained from a REST API call to your application's backend service.
The next step would be to get the user's preferred/ location zip code
var eje=document.getElementById('zip_code').value
now you can do a lookup in the above object model like
var zipCodeBasedAppUrl = zipCodeApps[eje];
if(undefined !== zipCodeBasedAppUrl) window.location.href = zipCodeBasedAppUrl;
This way your code looks nice, if you want to get the zip code specific URL for an input from the REST API, that would also be a good option considering the level of security and the sensitivity of the data your application has, choose the right approach.
HTH
function ver() {
var eje = document.getElementById('zip_code').value;
var che = document.getElementById('lugar').value;
var cheje = che.toLowerCase();
if (eje == 11385) {
window.location.assign("c:/users/lui/desktop/fluidimaging.html");
} else if(eje == 11386) {
window.location.assign("c:/users/lui/desktop/xyz.html");
} else {
alert("you did not enter a city or a zip code");
}
}

How to detect if a specific string (email domain) is entered into an input to add/remove attribute/class from a button

So I know how to do the remove/add class/attribute from a submit button, but I need to be able to apply this to a button based off of entry into an input.
The scenario is this, user enters their email address, but if it's at a specific domain, ex: xxxx#troopers.gov I then want to be able to apply/remove the class, and attribute from the submit button, since this is a domain they are not supposed to enter for a registration.
I have done some similar validation in the past, and tried a few different methods in jQuery .val(), indexOf, etc. But still can't seem to get it working.
I tried something like
var badDomain = 'troopers.gov';
and then
if (!$('#input').val() === badDomain) {
doStuff();
}
but it didn't seem to get me anywhere.
I thought I may be able to do this without using a RegEx (I don't have much experience with that)
Would be nice to be able to account for case as well... and I don't mind if the solution is jQuery, or pure JS... for learning purposes, it would be great to see how I could do it both ways...
So this does what you want, by turning anything typed into the field in lower case and then comparing against a given array of bad strings. Any time the input field blurs, it checks and turns the submit on or off.
Take a look in the code to see some bad addresses for sample use.
var badDomains = [
"troppers.com",
"fooBarBaz.org",
"myReallyUselessDomainName.com",
"a.net"
]
$(function(){
$("#email").on("blur", function(){
var addressBad = false;
var thisEmail = $(this).val().toLowerCase();
for (var i=0; i<badDomains.length; i++){
if (thisEmail.includes(badDomains[i])){
addressBad = true;
}
}
if (addressBad) {
console.log("bad address!")
$(".disabledButton").attr('disabled', "disabled");
} else {
console.log("not a bad address!");
$(".disabledButton").removeAttr("disabled");
}
})
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<label for="email">Email:</label>
<input type="text" name="email" id="email" />
<input class="disabledButton" type="submit" disabled />
</form>
simple workaround :
var email = document.getElementById('email');
var checkEmail = document.getElementById('checkEmail');
checkEmail.onclick = function() {
if ((email.value).includes('#troopers.gov')) alert('This email address cannot be used!');
}
<input id="email">
<button id="checkEmail">Check Email</button>
there are multiple ways around though.
You can use a regex for this purpose.
HTML:
<input type="text" id="InputTest" />
<button id="TestBtn" type="button">
Validate
</button>
<p>
Valid
</p>
CSS:
.valid{
background-color:green;
}
.invalid{
background-color: red;
}
JS:
$("#TestBtn").on("click",function() {
var pattern = /\S+#troopers\.com/gi;
var str = $("#InputTest").val();
var arr = str.match(pattern);
alert(arr); // just to see the value
if(arr !== null){
$("p").addClass("invalid");
}
else{
$("p").addClass("valid");
}
});
Here is a JSFiddle. Basically, if what the user typed in the textbox matches the expression.. then the background color turns red, but if it doesn't match, then the background color turns green.
Let me know if this helps.
You can use the following Regex for the Email property of the related Model in order to accept mails having 'abc.com' suffix:
[RegularExpression("^[a-zA-Z0-9_#./#&+-]+(\\.[a-zA-Z0-9_#./#&+-]+)*#abc.com$",
ErrorMessage = "Please enter an email with 'abc.com' suffix")]

Auto generate email based on username in WordPress

I've had some trouble getting this to work in the new user registration form, what I want is to have the email field automatically filled with a dummy email generated based on the username.
For example, if the user inputs user1 the generated email should be user1#test.com
I want it to be done in the new user form in case a user has a real email it can be specified instead of the dummy one.
What I've tried was some javascript and jQuery, but I can't get it to work, you can see the code below.
jQuery('#user_login').on('input propertychange paste', function()
{
var x = $('#user_login').val();
$($email).val( x + '#test.com');
});
Current javascript
<script>
$("user_login").change(function AutoEmail() {
var x= $('#user_login').val();
$('#email').val(x+'#test.com');
});
</script>
Also, where should this code be placed?, I'm a bit lost on the way things are organized in WordPress.
Try this.
$(document).on( "input", "#user_login", function AutoEmail() {
var x= $('#user_login').val();
if( x != "" ) {
$('#email').val(x+'#test.com');
} else {
$('#email').val("");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
Username: <input type = "text" id = "user_login"><br>
Email: <input type = "text" id = "email">

How to dynamically show error messages through PHP

I am creating a PHP login script. So far I have only worked on the registration.
My question is, how can I handle validation in PHP without refreshing the page? I want to output the feedback that the user has entered information wrongly, but I don't want to refresh the page. This is because I am using AJAX, so I want it to output on the page.
Is this possible?
See here, if you "sign up" without filling in any of the boxes it shows you some error messages. The problem is that it reloads the page as it does it. Is there a way to not reload the page and still show this data?
http://marmiteontoast.co.uk/fyp/login-register/test/index.php
This is an example of the if statement for just the username. This is repeated with all the other fields too:
if(isset($_POST['username'])){
$username = mysql_real_escape_string(trim($_POST['username']));
if(strlen($username) > 3){
// passed
if(strlen($username) < 31){
// passed
} else {
$_SESSION['status']['register']['error'][] = 'The Username is greater than 30 characters.';
}
} else {
$_SESSION['status']['register']['error'][] = 'The username is less than 4 characters.';
}
} else {
$_SESSION['status']['register']['error'][] = 'The Username is not entered.';
}
Once it passes all the validation it does:
header('Location:index.php');
And the errors are output on the index page by:
<?php
if(isset($_SESSION['status']['register']['error'])){
?>
<div class="alert alert-error">
<p><strong>There's a problem!</strong><br /><br />
<?php
foreach($_SESSION['status']['register']['error'] as $error){
// Outputs list of all errors, breaks to new line
echo $error . '<br />';
}
?>
</p>
1. Is it possible to output these dynamically with PHP?
2. Could I do the validation on the front end, then just pass it to the PHP to pass to the database?
2a. How would I handle running a username exists check if I do it front end?
This is something I actually just made the other day!
I have a file called "register.js", a file called "register_process.php" and some html.
How my server is set up:
html_docs (www):
ajax:
register_process.php
js:
register.js
jquery-1.6.2.js
register.html
so within my register.html, my code looks like such:
<script type="text/javascript" src="js/md5.js"></script> <!-- this is in my head -->
<script type="text/javascript" src="js/jquery-1.6.2.js"></script>
<!-- everything else is in my body -->
<div id="error_message" style="display: none;">
</div>
<div id="register_div">
<input type="text" name="username" id="username"><br>
<input type="password" name="password" id="password"><br>
<input type="submit" name="submitbutton" id="reg_button" value="Register" onclick="AttemptRegisterAjax(); return false;"><br>
</div>
This calls the function inside of my register.js file. That functions looks like such:
function AttemptAjaxRegister(){
var url = "ajax/register_process.php?";
url += "time=" + (new Date().getTime()) + "&un=";
var username_ele = document.getElementById("reg_username");
var password_ele = document.getElementById("reg_password");
var error_ele = document.getElementById("error_message");
var username = username_ele.value;
var password = password_ele.value;
if((username.length >=4) && (password.length >= 4)){
url += encodeURIComponent(username) + "&pw=" + encodeURIComponent(password);
console.log(url);
$.get(url, function(data, status, xhr){
data = data.trim();
if(data != "true"){
error_ele.innerText = data;
error_ele.style = "display: block;";
}else{
window.location = "/profile.php";
}
});
}else{
error_ele.innerText = "Please make sure your password and username are both 4 characters long";
error_ele.style = "display: block;";
}
}
now, inside of your php, you'll want to set everything up just like how you had it to register, but you'll want to actually just call die($YourErrorMessage); or if the registration was successful, die("true");
Not directly, you will need to use another tool for that, most likely Javascript.
Yes but that would be a terible practice. the best way to validate on both.
2a. I believe you would need to use a database.
thsi tutorials might help you out.
Easy jQuery Ajax PHP Contact Form
How to create a Sign Up form registration with PHP and MySQL

Categories

Resources