I want to give the registration is possible the user to download your picture.
I have custom user model:
class UserManager(BaseUserManager):
def create_user(self,username, email, password):
if not email:
raise ValueError('Email непременно должен быть указан')
user = self.model(
username = username,
email=UserManager.normalize_email(email),
)
user.set_password(password)
user.save(using=self._db)
return user
def create_superuser(self, username,email, password):
user = self.create_user(username, email, password)
user.is_superuser = True
user.is_admin = True
user.save(using=self._db)
return user
class ExtUser(AbstractBaseUser, PermissionsMixin):
email = models.EmailField(
'Электронная почта',
max_length=255,
unique=True,
blank=True
)
avatar = models.ImageField(
'Аватар',
blank=True,
null=True,
upload_to="user/avatar"
)
firstname = models.CharField(
'Фамилия',
max_length=40,
null=True,
blank=True
)
username = models.CharField(
_('username'),
max_length=30,
unique=True,
help_text=_('Required. 30 characters or fewer. Letters, digits and #/./+/-/_ only.'),
validators=[
validators.RegexValidator(
r'^[\w.#+-]+$',
_('Enter a valid username. This value may contain only '
'letters, numbers ' 'and #/./+/-/_ characters.')
),
],
error_messages={
'unique': _("A user with that username already exists."),
},
)
lastname = models.CharField(
'Имя',
max_length=40,
null=True,
blank=True
)
middlename = models.CharField(
'Отчество',
max_length=40,
null=True,
blank=True
)
date_of_birth = models.DateField(
'Дата рождения',
null=True,
blank=True
)
register_date = models.DateField(
'Дата регистрации',
auto_now_add=True
)
is_active = models.BooleanField(
'Активен',
default=True
)
is_admin = models.BooleanField(
'Суперпользователь',
default=False
)
balance = models.DecimalField(
'Деньги пользователя',
default=0.00,
decimal_places = 2,
max_digits = 200
)
subscriptions = models.ManyToManyField(Season, blank=True)
#
def get_full_name(self):
return self.email
#property
def is_staff(self):
return self.is_admin
def get_short_name(self):
return self.email
def __str__(self):
return self.username
USERNAME_FIELD = 'username'
REQUIRED_FIELDS = ['email']
objects = UserManager()
class Meta:
verbose_name = 'Пользователь'
verbose_name_plural = 'Пользователи'
register API:
#api_view(['POST'])
def register(request):
VALID_USER_FIELDS = [f.name for f in get_user_model()._meta.fields]
DEFAULTS = {
# you can define any defaults that you would like for the user, here
}
serialized = UserSerializer(data=request.data)
if serialized.is_valid():
user_data = {field: data for (field, data) in request.data.items() if field in VALID_USER_FIELDS}
user_data.update(DEFAULTS)
user = get_user_model().objects.create_user(
**user_data
)
return Response(UserSerializer(instance=user).data, status=status.HTTP_201_CREATED)
else:
return Response(serialized._errors, status=status.HTTP_400_BAD_REQUEST)
register function in JS controller:
$scope.register = function(email, password, username, avatar) {
return $http.post('/api/v1/auth/register/', {
username: username,
password: password,
email: email,
'avatar':avatar
}).success(function(data, status) {
return $scope.login(username, password)
window.location = '/'
})
}
HTML-form:
<form role="form" ng-submit="register(email,password,username, avatar)">
<div class="form-group">
<label for="register__email">Email</label>
<input type="email" class="form-control" id="register__email" ng-model="email" placeholder="email#email.com" />
</div>
<div class="form-group">
<label for="register__username">Username</label>
<input type="text" class="form-control" id="register__username" ng-model="username" placeholder="Bon Jovi" />
</div>
<div class="form-group">
<label for="register__username">Avatar</label>
<input name="pic" type="file" id="pic" accept="image/*">
</div>
<div class="form-group">
<label for="register__password">Password</label>
<input type="password" class="form-control" id="register__password" ng-model="password" placeholder='12345' />
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</form>
What do I need to do in terms of api , and javascript, to make it work ?
Related
I am trying to implement AJAX in my forms but I'm not able to submit optional QuerySelectField data to the database.
The field itself is populated with values from another table, it should be optional and hidden for users with lower access level (should ne NULL in such case). If selected, it should insert value of id column corresponding to the selected entry.
The problem is that AJAX seems to completely ignore it and always submits it as NULL.
I am completely new to this, tried searching for possible solution but couldn't find anything.
my forms.py:
class DodajAdmin(FlaskForm):
name = StringField(_l('Imię'), validators=[DataRequired()])
surname = StringField(_l('Nazwisko'), validators=[DataRequired()])
email = StringField(_l('Email'), validators=[DataRequired(), Email()])
phone = StringField(('Nr telefonu'), validators=[DataRequired(),
Length(min=8, max=12, message='Nieprawidłowy nr telefonu')])
PESEL = StringField(('PESEL'), validators=[DataRequired(), Length(min=11, max=11, message='Nieprawidłowy PESEL')])
pkk = StringField(('Numer PKK'), validators=[DataRequired(), Length(min=20, max=20, message='PKK musi składać się z dokładnie 20 znaków')])
res_city = StringField(('Miasto zamieszkania'), validators=[DataRequired()])
res_address = StringField(('Ulica i nr domu/mieszkania'), validators=[DataRequired()])
notes = StringField(('Uwagi'))
submit = SubmitField(_l('Dodaj kursanta'))
def validate_pkk(self, pkk):
kursant = Kursant.query.filter_by(PKK=pkk.data).first()
if kursant is not None:
raise ValidationError(_('Kursant o podanym numerze PKK już istnieje!'))
def validate_email(self, email):
kursant = Kursant.query.filter_by(email=email.data).first()
if kursant is not None:
raise ValidationError(_('Kursant o podanym adresie email już istnieje!'))
def validate_pesel(self, PESEL):
kursant = Kursant.query.filter_by(PESEL=PESEL.data).first()
if kursant is not None:
raise ValidationError(_('Kursant o podanym numerze PESEL już istnieje!'))
def instructors():
return User.query.all()
def getformclass():
formclass = DodajAdmin
if current_user.access_level > 1 :
setattr(formclass, "instructor", QuerySelectField('Instruktor prowadzący', query_factory=instructors, blank_text='Brak (jeszcze nie wybrano)', allow_blank=True))
return formclass
routes.py
#bp.route('/students/add/', methods=['GET', 'POST'])
#login_required
def dodaj_kursanta():
form_class = getformclass()
form = form_class()
access_level = User.query.filter(User.id == current_user.id)
icon = 'fas fa-user-plus'
if request.method == 'POST':
if form.validate():
if current_user.access_level > 1:
kursant = Kursant(name=form.name.data, surname=form.surname.data, email=form.email.data, PKK=form.pkk.data, \
PESEL=form.PESEL.data, phone=form.phone.data, res_city=form.res_city.data, res_address=form.res_address.data, instruktor=form.instructor.data, notes=form.notes.data, added_by=current_user.id)
kursant = Kursant(name=form.name.data, surname=form.surname.data, email=form.email.data, PKK=form.pkk.data, \
PESEL=form.PESEL.data, phone=form.phone.data, res_city=form.res_city.data, res_address=form.res_address.data, added_by=current_user.id)
db.session.add(kursant)
db.session.commit()
return '<div id="success-message" class="alert alert-success">Pomyślnie dodano kursanta.</div>'
return jsonify(form.errors), 400
return render_template('pages/dodaj-kursanta.html', title='Dodaj kursanta', form=form, icon=icon)
template
<form id="form" method="POST">
{{ form.csrf_token }}
<div class="text-danger my-2" id="csrf_token-error">
</div>
<div class="form-group">
{{ form.name(class="form-control", placeholder="Imię") }}
<div id="name-error" class="invalid-feedback"></div>
</div>
<div class="form-group">
{{ form.surname(class="form-control", placeholder="Nazwisko") }}
<div id="surname-error" class="invalid-feedback"></div>
</div>
<div class="form-group">
{{ form.email(class="form-control", placeholder="Adres email") }}
<div id="email-error" class="invalid-feedback"></div>
</div>
<div class="form-group">
{{ form.phone(class="form-control", type="number", placeholder="Telefon") }}
<div id="phone-error" class="invalid-feedback"></div>
</div>
<div class="form-group">
{{ form.PESEL(class="form-control", type="number", placeholder="PESEL") }}
<div id="pesel-error" class="invalid-feedback"></div>
</div>
<div class="form-group">
{{ form.pkk(class="form-control", placeholder="PKK") }}
<div id="pkk-error" class="invalid-feedback"></div>
</div>
<div class="form-group">
{{ form.res_city(class="form-control", placeholder="Miasto") }}
<div id="res_city-error" class="invalid-feedback"></div>
</div>
<div class="form-group">
{{ form.res_address(class="form-control", placeholder="Ulica/Dom") }}
<div id="res_address-error" class="invalid-feedback"></div>
</div>
{% if current_user.access_level > 1 %}
<div class="form-group">
<label class="my-1 me-2">Instruktor prowadzący</label>
{{ form.instructor(class="form-control") }}
</div>
{% endif %}
<div class="form-group">
{{ form.submit(class="btn-lg btn-primary", style="width: 100%") }}
</div>
</form>
<script>
const form = document.getElementById('form');
const successMessage = document.getElementById('success-message');
const fields = {
csrf_token: {
input: document.getElementById('csrf_token'),
error: document.getElementById('csrf_token-error')
},
name: {
input: document.getElementById('name'),
error: document.getElementById('name-error')
},
surname: {
input: document.getElementById('surname'),
error: document.getElementById('surname-error')
},
email: {
input: document.getElementById('email'),
error: document.getElementById('email-error')
},
phone: {
input: document.getElementById('phone'),
error: document.getElementById('phone-error')
},
PESEL: {
input: document.getElementById('PESEL'),
error: document.getElementById('pesel-error')
},
pkk: {
input: document.getElementById('pkk'),
error: document.getElementById('pkk-error')
},
res_city: {
input: document.getElementById('res_city'),
error: document.getElementById('res_city-error')
},
res_address: {
input: document.getElementById('res_address'),
error: document.getElementById('res_address-error')
},
instructor: {
input: document.getElementById('instructor'),
error: document.getElementById('instructor-error')
}
}
form.addEventListener('submit', async (e) => {
e.preventDefault();
const response = await fetch('/students/add/', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
csrf_token: fields.csrf_token.input.value,
name: fields.name.input.value,
surname: fields.surname.input.value,
email: fields.email.input.value,
phone: fields.phone.input.value,
PESEL: fields.PESEL.input.value,
pkk: fields.pkk.input.value,
res_city: fields.res_city.input.value,
res_address: fields.res_address.input.value,
instructor: fields.instructor.input.value
})
});
if (response.ok) {
successMessage.innerHTML = await response.text();
form.style.display = 'none';
successMessage.style.display = 'block';
} else {
const errors = await response.json();
Object.keys(errors).forEach((key) => {
fields[key].input.classList.add('is-invalid');
fields[key].error.innerHTML = errors[key][0];
});
}
});
</script>
Ok, I've managed to resolve the issue although I'm not certain why it behaved like described in the first place.
Turns out that moving second occurrence of variable 'kursant' in routes.py into else condition (see below) caused the form to pass all information correctly. For some reason it was attempting to insert the data twice within a single db session.
updated routes.py
#bp.route('/students/add/', methods=['GET', 'POST'])
#login_required
def dodaj_kursanta():
form_class = getformclass()
form = form_class()
access_level = User.query.filter(User.id == current_user.id)
icon = 'fas fa-user-plus'
if request.method == 'POST':
if form.validate():
if current_user.access_level > 1:
kursant = Kursant(name=form.name.data, surname=form.surname.data, email=form.email.data, PKK=form.pkk.data, \
PESEL=form.PESEL.data, phone=form.phone.data, res_city=form.res_city.data, res_address=form.res_address.data, instruktor=form.instructor.data, notes=form.notes.data, added_by=current_user.id)
else:
kursant = Kursant(name=form.name.data, surname=form.surname.data, email=form.email.data, PKK=form.pkk.data, \
PESEL=form.PESEL.data, phone=form.phone.data, res_city=form.res_city.data, res_address=form.res_address.data, added_by=current_user.id)
db.session.add(kursant)
db.session.commit()
return '<div id="success-message" class="alert alert-success">Pomyślnie dodano kursanta.</div>'
return jsonify(form.errors), 400
return render_template('pages/dodaj-kursanta.html', title='Dodaj kursanta', form=form, icon=icon)
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
Login.cshtml
<script type="text/javascript">
function data() {
var n = document.getElementById("username").value;
var m = document.getElementById("password").value;
?
</script>
<button type="submit"class="btn-login" onClick="Data()">
Giriş Yap </button>
Account Controller
DBEntities dB = new DBEntities();
[HttpPost] (username) (password)
public ActionResult Login(string KullaniciAdi,string Sifre)
{
// Session[KullaniciAdi] = dB.Profil.Where(x => x.KullaniciAdi == KullaniciAdi && x.Sifre == Sifre).FirstOrDefault();
var session = (from p in dB.Profil
where p.KullaniciAdi == KullaniciAdi
select p).FirstOrDefault();
return View();
}
My OOP homework is this website and i want to create a login with sending password and username to controller and compare submitted data and the data in the database .Please help :)
You can send client data by using ajax request,
this is your inputs
<input id="username" type="text" />
<input id="password" type="password" />
<input id="loginbutton" onclick="UserLogin()" type="submit" value="Submit" />
Submit button bind with UserLogin js function.
here is the js function. we are sending ajax post request here to our controller
<script type="text/javascript">
function UserLogin() {
var n = document.getElementById("username").value;
var p = document.getElementById("password").value;
var postObj = JSON.stringify({
"username": n,
"password": p
});
$.ajax({
url: "/Home/Login", // endpoint
type: "POST",
data: postObj,
contentType: "application/json; charset=utf-8",
success: function (result) {
// success
},
error: function (errorData) { onError(errorData); }
});
}
</script>
And your controller should be like, you can implement login logic inside of the method.
[HttpPost]
public ActionResult Login(string username, string password)
{
// use your code loged in
return Json(true, JsonRequestBehavior.AllowGet);
}
First You Create a Class :
public class LoginModel
{
[Required(ErrorMessage = "User Name can not be empty!")]
public string LOGINID { get; set; }
[Required(ErrorMessage = "Password can not be empty!")]
public string LOGINPW { get; set; }
}
Then Your Controller Action Method do this:
public ActionResult Login()
{
return View();
}
[HttpPost]
public ActionResult Login(LoginModel model)
{
//Here check the Login Id and Password
return View();
}
Now in view Write this. Now when you click the submit button a post call go to the Login Controller with given LOGINID and LOGINPW :
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
<!-- login screen -->
<form action="#">
#Html.TextBoxFor(m => m.LOGINID, htmlAttributes: new { #class = "form-control", placeholder = "Login ID" })
#Html.ValidationMessageFor(model => model.LOGINID, "", new { #class = "text-danger", style = "float: left" })
#Html.PasswordFor(m => m.LOGINPW, htmlAttributes: new { #class = "form-control", placeholder = "Password" })
#Html.ValidationMessageFor(model => model.LOGINPW, "", new { #class = "text-danger", style = "float: left" })
<button type="submit" class="btn btn-primary" style="background: #2e6da4; color: #FFF;">Login</button>
</form>
}
#{
var actionURL = Url.Action("Action", "Controller",
FormMethod.Post, Request.Url.Scheme)
+ Request.Url.PathAndQuery;
}
#using (Html.BeginForm("Action", "Controller", FormMethod.Post,
new { #action = actionURL }))
{
<input type="text" name="username">
<input type="text" name="password">
<button type="submit"class="btn-login"></button>
}//Then use Request.Form[0] with the id to get the user name and password in the controller action.
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)
}
});