Hi I'd like to have new users register their name and password and have it pushed into the users array. It works in plain Javascript, but for some reason my Angular JS won't.
HERES THE ANGULAR JS
var users = [
{
username: 'Regie',
password: 'Tano'
},
{
username: 'Jacob',
password: 'Minshall'
},
{
username: 'Greg',
password: 'Mayer'
}
]
app.controller("logIn", function($scope){
$scope.log = function(){
//Get Values of Inputs for username and password
var username= document.getElementById('username').value
var password = document.getElementById('password').value
//Loop through users to check if username and password are correct.
for(i = 0; i < users.length; i++){
if(username == users[i].username && password == users[i].password){
alert('That Username or Password is already taken')
}
}
}
});
//REGISTER USER**********
app.controller("registerUser", function($scope){
$scope.place = function(){
var registerName = document.getElementById('registerName').value
var registerPass = document.getElementById('registerPass').value
var newUser = {
username: registerName,
password: registerPass
}
users.push(newUser)
console.log(users)
}
});
HERE'S THE HTML
<body ng-app='myApp'>
<form id='form' ng-controller='logIn'>
<h1>Log In</h1>
<input type="text" id="username" placeholder="Enter Username" />
<input type="password" id="password"placeholder="Enter Password" />
<button id="button" type="button" ng-click='log()'>Click This</button>
</form>
<form id='form2' ng-controller='registerUser'>
<h1>Register</h1>
<input type='text' id='registerName' placeholder='Enter Username'/>
<input type='password' id='registerPass' placeholder='Enter Password'/>
<button id='registerButton' type='button' ng-click='place()'>Register</button>
</form>
In angular you should not access to the DOM directly, instead use directives as ng-model.
So, you html should be something like this:
<body ng-app='myApp'>
<form id='form' ng-controller='logIn'>
<h1>Log In</h1>
<!-- Using ng-model is how you bind data from the view to the controller in AngularJS -->
<input type='text' ng-model='username' placeholder='Enter Username' />
<input type='password' ng-model='password' placeholder='Enter Password' />
<!-- we send the binded data to the function as parameters -->
<button id="button" type="button" ng-click='log(username, password)'>Click This</button>
</form>
<form id='form2' ng-controller='registerUser'>
<h1>Register</h1>
<!-- Using ng-model is how you bind data from the view to the controller in AngularJS -->
<input type='text' ng-model='registerName' placeholder='Enter Username'/>
<input type='password' ng-model='registerPass' placeholder='Enter Password'/>
<!-- we send the binded data to the function as parameters -->
<button id='registerButton' type='button' ng-click='place(registerName, registerPass)'>Register</button>
</form>
</body>
And your controllers:
var users = [
{
username: 'Regie',
password: 'Tano'
},
{
username: 'Jacob',
password: 'Minshall'
},
{
username: 'Greg',
password: 'Mayer'
}
]
app.controller("logIn", function($scope){
// This is the username and password in the html
$scope.username = ''; // ng-model="username"
$scope.password = ''; // ng-model="password"
$scope.log = function(username, password){
//Loop through users to check if username and password are correct.
for(i = 0; i < users.length; i++){
if(username == users[i].username && password == users[i].password){
alert('That Username or Password is already taken')
}
}
}
});
//REGISTER USER**********
app.controller("registerUser", function($scope){
// This is the registerName and registerPass in the html
$scope.registerName = ''; // ng-model="registerName"
$scope.registerPass = ''; // ng-model="registerPass"
// Instead of read the data in the model, we pass them as parameters. Doing this is better for testing.
$scope.place = function(registerName, registerPass){
var newUser = {
username: registerName,
password: registerPass
}
users.push(newUser)
console.log(users)
}
});
Related
Getting Local storage is missing an ID Token, Please authenticate. My end goal is to get the user signed up through AWS Cognito and then add a row in my DynamoDB table. I am able to get the user in the user pool but not able to add the details to DynamoDB. Unable to figure out the error any help will be appreciated.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<!-- Javascript SDK-->
<script src="https://sdk.amazonaws.com/js/aws-sdk-2.410.0.min.js"></script>
<script src="https://rawgit.com/aws/amazon-cognito-identity-js/master/dist/aws-cognito-sdk.min.js"></script>
<script src="https://rawgit.com/aws/amazon-cognito-identity-js/master/dist/amazon-cognito-identity.min.js"></script>
</head>
<body>
<fieldset >
<h1 class="h3 mb-3 font-weight-normal" id="titleheader">Register an Account</h1>
<form>
<input type="email" class="form-control" id="emailInputRegister" placeholder="Email" pattern=".*" required><br><br>
<input type="password" class="form-control" id="passwordInputRegister" placeholder="Password" pattern=".*" required><br><br>
<input type="personalname" class="form-control" id="personalnameRegister" placeholder="First Name" pattern=".*" required><br><br>
<input type="personalname2" class="form-control" id="personalnameRegister2" placeholder="Last Name" pattern=".*" required><br><br>
<input type="text" class="form-control" id="organizationRegister" placeholder="Organization" pattern=".*" required><br><br>
<input type="text" class="form-control" id="jobTitleRegister" placeholder="JobTitle" pattern=".*" required><br><br>
<input type="tel" class="form-control" id="phone" placeholder="Cell Phone Number" pattern=".*" required><br><br>
<button id="mainbutton" class="btn btn-lg btn-primary btn-block" type="button" onclick="registerButton()" >Sign Up</button>
</form>
</fieldset >
<script>
var username;
var password;
var firstname;
var lastname;
var jobtitle;
var organization;
var phonenumber;
var poolData;
function registerButton() {
username = document.getElementById("emailInputRegister").value;
password = document.getElementById("passwordInputRegister").value;
firstname = document.getElementById("personalnameRegister").value;
lastname = document.getElementById("personalnameRegister2").value;
organization = document.getElementById("organizationRegister").value;
jobtitle = document.getElementById("jobTitleRegister").value;
phonenumber = document.getElementById("phone").value;
poolData = {
UserPoolId :<userPoolId>,
'
ClientId : <client id>
};
var userPool = new AmazonCognitoIdentity.CognitoUserPool(poolData);
var attributeList = [];
var dataEmail = {
Name : 'email',
Value : username, //get from form field
};
var dataFirstName = {
Name : 'name',
Value : firstname, //get from form field
};
/*var dataLastName ={
Name : 'family name',
Value : lastname,
};
var dataPhoneNumber ={
Name : 'family name',
Value : lastname,
};*/
var attributeEmail = new AmazonCognitoIdentity.CognitoUserAttribute(dataEmail);
var attributePersonalName = new AmazonCognitoIdentity.CognitoUserAttribute(dataFirstName);
attributeList.push(attributeEmail);
attributeList.push(attributePersonalName);
var temp;
userPool.signUp(username, password, attributeList, null, function(err, result){
if (err) {
alert(err.message || JSON.stringify(err));
return;
}
cognitoUser = result.user;
console.log('user name is ' + cognitoUser.getUsername());
//var cognitoUser = userPool.getCurrentUser();
//console.log('cognitoUser =',cognitoUser);
//change elements of page
//document.getElementById("titleheader").innerHTML = "Check your email for a verification link";
//});
//var userPool1 = new AWSCognito.CognitoIdentityServiceProvider.CognitoUserPool(data);
//console.log('userPool',userPool1);
//var cognitoUser = userPool1.getCurrentUser();
//console.log("temp is ", cognitoUser);
if (cognitoUser != null) {
cognitoUser.getSession(function(err, session) {
if (err) {
console.log(err);
return;
}
console.log('session validity: ' + session.isValid());
console.log('session token: ' + session.getIdToken().getJwtToken());
AWS.config.region = 'us-east-1';
AWS.config.credentials = new AWS.CognitoIdentityCredentials({
IdentityPoolId : <Identity_Pool>,
Logins : {
// Change the key below according to the specific region your user pool is in.
'cognito-idp.us-east-1.amazonaws.com/${Identity_Pool}' : session.getIdToken().getJwtToken()
}
});
AWS.config.credentials.get(function(err) {
if (!err) {
var id = AWS.config.credentials.identityId;
console.log('Cognito Identity ID '+ id);
// Instantiate aws sdk service objects now that the credentials have been updated
var docClient = new AWS.DynamoDB.DocumentClient({ region: AWS.config.region });
var params = {
TableName: 'TestTable',
Item:{emailId:username, }
};
docClient.put(params, function(err, data) {
if (err)
console.error(err);
else
console.log(data);
});
}
});
});
} else {
console.log(err);
return;
}
});
}
</script>
</body>
</html>
You can use an API for Dynamodb operations with docClient.put()
I have a register form which works with Vue and local storage, when I submit the form blank or leave out an input the data is going to the local storage the same and not showing the HTML validation which is used by adding required attribute. Is there any way I can fix this problem by showing the HTML validation if the form has inputs which are empty or if the email do not have an at-sign inserted.
Form:
<form id="signup" method="post" v-on:submit.prevent>
<br>
<h1>Registration</h1>
<label for ="studentsorparents">Student or parents:</label>
<input type="text" id="studentsorparents" v-model="studentsorparents" required ="required">
<br><br>
<label for ="username">username:</label>
<input type="text" id="username" v-model="username" required ="required" v-text="null">
<br><br>
<label for="email">email: </label>
<input type="email" id="email" v-model='email' required ="required">
<br><br>
<label for="password">password: </label>
<input type="password" id="password" v-model='password' required ="required">
<br><br>
<button v-on:click='onSubmit' onclick="passuseremail()" >Register</button>
</form>
JS:
var signupApp = new Vue({
el: '#signup',
data: {
studentsorparents: '',
username: '',
email: '',
password: '',
},
methods: {
onSubmit: function () {
// check if the email already exists
var users = '';
var studentParent = this.studentsorparents;
var newUser = this.username;
var newEmail = this.email;
if (localStorage.getItem('users')) { // 'users' is an array of objects
users = JSON.parse(localStorage.getItem('users'));
}
if (users) {
if (users.some(function (user) {
return user.username === newUser
})) {
alert('Account already exits');
return;
}
if (users) {
if (users.some(function (user) {
return user.email === newEmail
})) {
alert('Account already exits');
return;
} else {
alert('Account created');
window.location.href = 'user-profile.html' + '#' + newUser;
}
}
users.push({
'studentsorparents': studentParent,
'username': newUser,
'email': newEmail,
'password': this.password
});
localStorage.setItem('users', JSON.stringify(users));
} else {
users = [{
'studentparents': studentParent,
'username': newUser,
'email': newEmail,
'password': this.password
}];
localStorage.setItem('users', JSON.stringify(users));
}
}
}
});
function passuseremail()
{
var username = document.getElementById('username').value;
localStorage.setItem("user-check", username);
var studentsorparents=document.getElementById('studentsorparents').value;
localStorage.setItem("students-parents-check", studentsorparents)
var email=document.getElementById('email').value;
localStorage.setItem("email-check", email)
return false
}
You need to add button type='submit' to the submit button else it will behave like just any other button.
<button v-on:click='onSubmit' onclick="passuseremail()" type="submit">Register</button>
It then only act as submit button else it will just trigger the button eventlisteners attached.
You have spaces after required attributes in your inputs:
required ="required"
It's incorrect and it will not work; just write it like this:
<input type=email id=email v-model=email required>
You can validate email like this:
const email_re = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+#[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+$/;
if (email_re.test( email.value )) {
/* email is valid */
} else {
/* email is not valid */
}
You can add a class to the button like jsValidateRegister.
And the add the code
First declare a variable
isPageValid = true
Then in add the following code for validation so the isPageValid is set to false inside the passuseremail();
$(".jsValidateRegister").click(function ()
{
passuseremail();
});
In the onSubmit: function () check
isPageValid === true
Hi I'd like my Angular JS form to be able to confirm that someone's log in information is correct when it's typed into the input. Am I doing this right?
HERE'S THE ANGULAR JS
var app= angular.module('multiPageApp', []);
//SET UP: Array of users
app.controller('logIn', function($scope){
$scope.users = [
{
username: 'Regie',
password: 'Tano'
},
{
username: 'Jacob',
password: 'Minshall'
},
{
username: 'Greg',
password: 'Mayer'
}
]
$scope.log = function(){
//Get Values of Inputs for username and password
var username= document.getElementById('input').value
var password = document.getElementById('password').value
//Loop through users to check if username and password are correct.
for(i = 0; i < users.length; i++){
if(username == users[i].username && password == users[i].password){
console.log('it worked!')
}
}
}
});
First, use angular $scope variables in order to get the input and password fields.
You can define them associated to your inputs as below:
<input type="text" id="input" ng-model="username" placeholder="Type your username..." />
Then, you can use the JavaScript filter (or also find if you are using ECMA6) method in order to get the match:
if (users.filter(checkCredentials).length > 0) {
// ok case.
}
else {
// error case. Use ngMessages to show errors in the form
}
function checkCredentials(element) {
return element.username === $scope.username && element.password === $scope.password;
}
Best way in angular to display error validation is using ngMessages:
https://docs.angularjs.org/api/ngMessages/directive/ngMessages
You should use ng-model to capture the value entered in textbox as follows:
<input type="text" id="username" ng-model="username" placeholder="Enter username" />
<input type="password" id="password" ng-model="password" placeholder="Enter password" />
And in your controller check in this way:
var app= angular.module('multiPageApp', []);
//SET UP: Array of users
app.controller('logIn', function($scope){
$scope.users = [
{
username: 'Regie',
password: 'Tano'
},
{
username: 'Jacob',
password: 'Minshall'
},
{
username: 'Greg',
password: 'Mayer'
}
]
$scope.log = function(){
//Loop through users to check if username and password are correct.
for(i = 0; i < users.length; i++){
if(username == users[i].username && password == users[i].password){
console.log('it worked!')
}
}
}
});
I use angular2 + firebase.
There's something wrong in my code.
When user is logged in, functions createUser and removeUser doesn't work without errors. Without logging in it works properly. I got parts of code from firebase tutorial. The same thing when i'm trying to use google auth service.
app.controller("AuthCtrl", ["$scope", "$firebaseAuth",
function($scope, $firebaseAuth) {
var ref = new Firebase("...");
var Auth = $firebaseAuth(ref)
$scope.createUser = function() {
$scope.message = null;
$scope.error = null;
Auth.$createUser({
email: $scope.email,
password: $scope.password
}).then(function(userData) {
$scope.message = "User created with uid: " + userData.uid;
$scope.email = "";
$scope.password = "";
}).catch(function(error) {
$scope.error = error;
});
};
$scope.removeUser = function() {
$scope.message = null;
$scope.error = null;
Auth.$removeUser({
email: $scope.email,
password: $scope.password
}).then(function() {
$scope.message = "User removed";
$scope.email = "";
$scope.password = "";
}).catch(function(error) {
$scope.error = error;
});
};
$scope.login = function(){
Auth.$authWithPassword({
email: $scope.emaillog,
password: $scope.passwordlog
}).then(function(authData) {
$scope.authData = Auth.$getAuth();
console.log("Logged in as:", authData.uid);
}).catch(function(error) {
console.error("Authentication failed:", error);
});
}
}
]);
<div ng-app="App">
<div ng-controller="AuthCtrl">
<div>
<h2>Login</h2>
<form>
Email: <input ng-model="emaillog" type="text" placeholder="email">
Password: <input ng-model="passwordlog" type="text" placeholder="password">
<br><br>
<button ng-click="login()">Login</button>
</form>
</div>
<div ng-if = "authData">
<h2>Managing users</h2>
<form>
Email: <input ng-model="email" type="text" placeholder="email">
Password: <input ng-model="password" type="text" placeholder="password">
<br><br>
<button ng-click="createUser()">Create User</button>
<button ng-click="removeUser()">Remove User</button>
<p ng-if="message">Message: <strong>{{ message }}</strong></p>
<p ng-if="error">Error: <strong>{{ error }}</strong></p>
</form>
</div>
</div>
</div>
I've found the answer here what is the difference between ng-if and ng-show/ng-hide
I have Express.js server. Running in node.js. Using javascript server side language. There I have signup sipmle form, register new user and save users in mongoDb. POST method.
<form action="/new" method="POST">Name:
<input type="text" name="name" class="name"/><br/>Phone number:
<input type="text" name="phone" class="phone"/><br/>email:
<input type="email" name="email" class="email"/><br/>Password:
<input type="password" id="p1" name="pass" class="pass"/><br/>Confirm password:
<input type="password" id="p2" name="confirm" class="confirm"/><br/>
<input type="submit" value="Submit" onclick="return validateForm()"/>
</form>
Need to create input validation(actualy it's "Password confirm" and "Email")Also need to use "regex". How I can realize this method?I created input data validation on client-side.It's works.Maybe I just need put this code in the server? Searching in google don't give me expected results... I saw many validation methods validator.js but not finde detailed code...Thank you for helping:)
<script>
function validateForm (event) {
var p1 = document.getElementById('p1');
var p2 = document.getElementById('p2');
if (p1.value !== p2.value) {
alert('Password check!');
return false;
}
// check email
var email = document.getElementById('email');
// regex
var email_regexp = /[0-9a-zа-я_A-ZА-Я]+#[0-9a-zа-я_A-ZА-Я^.]+\.[a-zа-яА-ЯA-Z]{2,4}/i;
if (!email_regexp.test(email.value)) {
alert('Check email');
return false;
}
}
</script>
also here is my registration server side code:
app.use(bodyParser());
mongoose.connect('mongodb://localhost/test');
var Schema = new mongoose.Schema({
name : String,
phone: String,
email : String,
pass : String,
confirm : String
});
var user = mongoose.model('emp', Schema);
app.post('/new', function(req, res){
new user({
name : req.body.name,
phone: req.body.phone,
email: req.body.email,
pass: req.body.pass,
confirm: req.body.confirm
}).save(function(err, doc){
console.log(user);
if(err) res.json(err);
else res.send('Successfully inserted!');
});
});
For validating email you should use-
req.checkBody('email').isEmail();
For the validation of Password and Confirm Password you should use-
req.assert('confirm', 'Password and Confirm Password should be same.').equals(req.body.pass);
var mappedErrors = req.validationErrors(true);