function checkRegisterError() {
const xhr = new XMLHttpRequest();
xhr.open("GET", "http://ipaddressandport/users/register");
xhr.onload = () => {
console.log("tes");
if (xhr.status === 400) {
console.log("rip");
}
};
xhr.send();
}
const signupBtn = document.querySelector(".signup-form-btn");
if (signupBtn) {
signupBtn.addEventListener("click", () => {
console.log("ok");
checkRegisterError();
});
}
I'm using nodejs and express. So I have this applied on my register button which is also a type submit for a form with an action of /users/register. On my node I have this code which is registered to /users/register:
exports.addUser = (request, respond) => {
if (
!request.body.firstName ||
!request.body.lastName ||
!request.body.email ||
!request.body.username ||
!request.body.password ||
!request.body.gender ||
!request.body.mobileNumber ||
!request.body.address
) {
respond.status(400).send("error empty input etc etc");
} else {
db.execute(
"INSERT INTO users(firstName, lastName, email, username, password, gender, mobileNumber, address, profilePictureUrl) VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?)",
[
request.body.firstName,
request.body.lastName,
request.body.email,
request.body.username,
request.body.password,
request.body.gender,
request.body.mobileNumber,
request.body.address,
"https://www.eurogeosurveys.org/wp-content/uploads/2014/02/default_profile_pic.jpg",
]
)
.then((result) => {
console.log(result);
respond.redirect("/");
})
.catch((err) => console.log(err));
}
};
The problem is whenever I press register the forms goes to the route and it will be a blank page of whatever I sent, and there will be no logged output. I want to change certain element properties depending on what the message and status code is. How could I do that? Why am I getting directed to an empty page with the text I sent?
<form class="sign-up-form" action="/users/register" method="POST">
<div class="nav-name">
<input name="firstName" type="text" class="input first-name" placeholder="First name">
<input name="lastName" type="text" class="input last-name" placeholder="Last name">
</div>
<input name="email" type="text" class="input email" placeholder="Email">
<input maxlength="16" name="username" type="text" class="input username" placeholder="User ID">
<div class="password-container">
<input maxlength="16" name="password" type="password" class="input password" placeholder="Password">
<label class="toggle-password" for="toggle-password-register">
<i class="show-password fas fa-eye"></i>
<i class="hide-password fas fa-eye-slash"></i>
</label>
<input id="toggle-password-register" type="checkbox" class="toggle-password__input">
</div>
<input name="gender" type="text" class="input gender" placeholder="Gender">
<input name="mobileNumber" type="text" maxlength="8" class="input mobile-number"
placeholder="Mobile number">
<input name="address" type="text" class="input address" placeholder="Address">
<button type="submit" class="form-btn signup-form-btn">Sign up</button>
</form>
You are getting redirected to empty page because you have written response.redirect('/') , you should check if Db operation is successful then according to that send response to user .
Related
I'm working with DOM and web API to POST some information about the company like name, worker's name.
But when I write something in the input DOM can't reach the value and return empty so I post an empty object.
That looks like :
adress: ""
companyName: ""
contactName: ""
contactTitle: ""
My form block:
<form>
<div class="form-group">
<label for="">Company Name</label>
<input
type="text"
class="form-control"
id="companyName"
placeholder="Company Name!"
/>
</div>
<div class="form-group">
<label for="">Contact Name</label>
<input
type="text"
class="form-control"
id="contactName"
placeholder="Contact Name!"
value=""
/>
</div>
<div class="form-group">
<label for="">Contact Title</label>
<input
type="text"
class="form-control"
id="contactTitle"
placeholder="Contact Title!"
/>
</div>
<div class="form-group">
<label for="">Country</label>
<input
type="text"
class="form-control"
id="inputCountry"
placeholder="Country!"
/>
</div>
</form>
And my JS code:
'use strict';
let inputCompanyName = document.getElementById('companyName');
let inputContactName = document.getElementById('contactName');
let inputContactTitle = document.getElementById('contactTitle');
let country = document.getElementById('inputCountry');
const btnSubmit = document.getElementById('submit');
let newCompany = {
companyName: inputCompanyName.value,
contactName: inputContactName.value,
contactTitle: inputContactTitle.value,
adress: country.value,
};
btnSubmit.addEventListener('click', e => {
e.preventDefault();
axios
.post('https://northwind.vercel.app/api/suppliers', newCompany)
.then(res => {
console.log('Response', res.data);
alert('Success!');
});
});
I tried innerHTML and innerText and form method but I cant solve this problem.
You're reading the values immediately upon loading the page, long before the user has had a chance to enter any values.
Instead, read the values in the click event:
btnSubmit.addEventListener('click', e => {
let newCompany = {
companyName: inputCompanyName.value,
contactName: inputContactName.value,
contactTitle: inputContactTitle.value,
adress: country.value,
};
// the rest of the click handler logic...
});
Trying to use simple JS to validate user password when registering, however page does not display any errors and runs as if the JS doesn't even exist (though it is added at the end of php file <script src="script.js"></script>). Any suggestions on what I am doing wrong are welcome, as I can't seem to figure it out. I am completely new to JS but need to do this for school, was trying to implement it in the simplest possible way.
Example of JS:
const name = document.getElementById('name')
const password = document.getElementById('password')
const form = document.getElementById('registerForm')
const errorElement = document.getElementById('error')
const button = document.getElementById('signUp')
if (button) {
form.addEventListener(button, (e) => {
let messages = []
if (name.value === '' || name.value == null) {
messages.push('Name is required.')
}
if (password.value.length <= 6) {
messages.push('Password must be longer than 6 characters.')
}
if (password.value.length >= 20) {
messages.push('Password must be less than 20 characters.')
}
if (messages.length > 0) {
e.preventDefault()
errorElement.innerText = messages.join(', ')
}
})
}
The snip from html:
<form id="registerForm" class="register" method="post">
<div id = "signup_form" class="textboxes">
<input id="name" type = "text" name="name" placeholder="Name">
<input id="email" type = "email" name="email" placeholder="Email">
<input id="password" type = "password" name="password" placeholder="Password">
<input id="repeat_password" type = "password" name="password_again" placeholder="Repeat password">
<button id="signUp" type="submit" name="btn-register">Sign Up</button>
<div id = "error"></div>
You just missed a few things. The formatting of your HTML was not proper, and to add an event listener, you need to use the form target.addEventListener(type, listener [, options]);
Here, you want to have the "target" be the button since this is triggering the action. See here for more info.
const name = document.getElementById('name')
const password = document.getElementById('password')
const form = document.getElementById('registerForm')
const errorElement = document.getElementById('error')
const button = document.getElementById('signUp')
if (button) {
button.addEventListener('click', (e) => {
let messages = []
if (name.value === '' || name.value == null) {
messages.push('Name is required.')
}
if (password.value.length <= 6) {
messages.push('Password must be longer than 6 characters.')
}
if (password.value.length >= 20) {
messages.push('Password must be less than 20 characters.')
}
if (messages.length > 0) {
e.preventDefault()
errorElement.innerText = messages.join(', ')
}
})
}
<form id="registerForm" class="register" method="post">
<div id="signup_form" class="textboxes">
<input id="name" type="text" name="name" placeholder="Name" />
<input id="email" type="email" name="email" placeholder="Email" />
<input id="password" type="password" name="password" placeholder="Password" />
<input id="repeat_password" type="password" name="password_again" placeholder="Repeat password" />
<button id="signUp" type="submit" name="btn-register">Sign Up</button>
<div id="error"></div>
</div>
</form>
form.addEventListener(button doesn't make any sense. You have to tell addEventListener the name of an event to listen out for. In this case, the "submit" event of the form is the one you ought to be listening to.
Also the if(button) block didn't seem to have any useful purpose, so I removed that too, and the HTML snippet you provided was missing a couple of closing tags from the end.
Working demo:
const name = document.getElementById('name')
const password = document.getElementById('password')
const form = document.getElementById('registerForm')
const errorElement = document.getElementById('error')
const button = document.getElementById('signUp')
form.addEventListener("submit", (e) => {
let messages = []
if (name.value === '' || name.value == null) {
messages.push('Name is required.')
}
if (password.value.length <= 6) {
messages.push('Password must be longer than 6 characters.')
}
if (password.value.length >= 20) {
messages.push('Password must be less than 20 characters.')
}
if (messages.length > 0) {
e.preventDefault()
errorElement.innerText = messages.join(', ')
}
})
<form id="registerForm" class="register" method="post">
<div id="signup_form" class="textboxes">
<input id="name" type="text" name="name" placeholder="Name">
<input id="email" type="email" name="email" placeholder="Email">
<input id="password" type="password" name="password" placeholder="Password">
<input id="repeat_password" type="password" name="password_again" placeholder="Repeat password">
<button id="signUp" type="submit" name="btn-register">Sign Up</button>
<div id="error"></div>
</div>
</form>
P.S. It's also worth noting that the validation you've got here is very simple, and you could achieve the same results using HTML5 validation, just by adding attributes to your HTML form elements, and you wouldn't need to write any JavaScript at all:
<form id="registerForm" class="register" method="post">
<div id="signup_form" class="textboxes">
<input id="name" type="text" name="name" placeholder="Name" required>
<input id="email" type="email" name="email" placeholder="Email">
<input id="password" type="password" name="password" placeholder="Password" required minlength="6" maxlength="20">
<input id="repeat_password" type="password" name="password_again" placeholder="Repeat password" required minlength="6" maxlength="20">
<button id="signUp" type="submit" name="btn-register">Sign Up</button>
<div id="error"></div>
</div>
</form>
I'm a newbie to angular, so I need a help.
In html, I wrote the following
<div class="form-group">
<input type="email" name="Email" id="LoginEmail class="form-control" placeholder="Email Address" required>
</div>
<div class="form-group">
<input type="password" name="password" id="LoginPassword" class="form-control" placeholder="Password" required>
</div>
In angular, I write the following code
angular
.module("LoginForm", [])
.controller("processingLoginForm", ["$scope", function ($scope) {
$scope.userinfo = [
{name : "User1",
account : "user1#whatever.com",
city: "XYZ",
password: "Angular#2017"}
];
}]);
I need to compare the value of input box with the value of the script and show a message if it's not correct, so how can I do that?
Firstly you need to assign model to your template scope. Use ng-model for this purpose. Then you need a form to submit and trigger a function to check if user input matches to the desired values.
Add ng-model and wrap your inputs with a form tag:
<form ng-submit="login()">
<div class="form-group">
<input ng-model="email" type="email" name="Email" id="LoginEmail" class="form-control" placeholder="Email Address" required>
</div>
<div class="form-group">
<input ng-model="password" type="password" name="password" id="LoginPassword" class="form-control" placeholder="Password" required>
</div>
<button type="submit">Login</button>
</form>
Check if user input is valid in Controller:
$scope.login = function() {
const isUserValid = $scope.email === $scope.userinfo[0].account && $scope.password === $scope.userinfo[0].password;
if(isUserValid) {
alert("Logged In Successfully");
}else {
alert("Email or password incorrect. Try again.")
}
}
Here's a working example of the above code.
In your input elements you miss the ng-model attribute. It is used to bind the values with your scope variables.
<input type="email" ... ng-model="email" ...>
<input type="password" ... ng-model="password" ...>
And in your controller you can write
if($scope.email == $scope.userinfo[0].account && $scope.password == $scope.userinfo[0].password){
//Login ok
}else{
//Login failed
}
Assuming there is a form element somewhere above
Add ng-submit to it
<form ng-submit="submit()">
Add ng-model to the form elements.
I have added state.email and state.password
<div class="form-group">
<input ng-model="state.email" type="email" name="Email" id="LoginEmail" class="form-control" placeholder="Email Address" required>
</div>
<div class="form-group">
<input ng-model="state.password" type="password" name="password" id="LoginPassword" class="form-control" placeholder="Password" required>
</div>
Compare the binding values to the values in $scope.userinfo
angular
.module("LoginForm", [])
.controller("processingLoginForm", ["$scope", function ($scope) {
$scope.userinfo = [{
name : "User1",
account : "user1#whatever.com",
city: "XYZ",
password: "Angular#2017"
}];
// when you submit the form, this function will be called
$scope.submit = function (e) {
e.preventDefault();
if ($scope.state.email !== $scope.userinfo[0].account || $scope.state.password !== $scope.userinfo[0].password) {
// did not match
} else {
// matched
}
}
}]);
This is my first bigger form with validations and etc.
I've created a Registration form and I'm using ng-messages for validation. The problem is that I need to validate the username, does it already exist in the JSON server that we are using or it's available. Of course, if it's taken the warning pops out in the HTML where the username input is, if it's available the submit button is no more disabled (because the form will be $valid) and the user can register. I want to use angular-sanitize because I found this (I don't know if they are related):
ngModel.$asyncValidators.uniqueUsername = function(modelValue, viewValue) {
var value = modelValue || viewValue;
// Lookup user by username
return $http.get('/api/users/' + value).
then(function resolved() {
//username exists, this means validation fails
return $q.reject('exists');
}, function rejected() {
//username does not exist, therefore this validation passes
return true;
});
};
Here is the code I use now (reg form, controller and service):
// Controller:
export default class registerPageController {
constructor(userService, authenticationService, $location) {
this.register = "Register";
this.userService = userService;
this.$location = $location;
this.authenticationService = authenticationService;
this.hasLoggedIn = false;
}
onSubmit(user) {
let self = this;
let {
name,
age,
email,
username,
password
} = user;
self.userService.register(name, age, email, username, password).then((res) => {
self.userService.login(username, password).then(function (response) {
let data = response.data;
if (data.length) {
let user = data[0];
self.hasLoggedIn = true;
self.authenticationService.setCredentials(username, password);
self.$location.path('/');
}
});
})
.catch(err => {
// WHAT TO PUT HERE AFTER THE USERNAME EXIST VALIDATION ?
})
}
}
// Service:
export class UserService {
constructor($http) {
this.$http = $http;
}
login(username, password) {
return this.$http({
method: 'GET',
url: 'http://localhost:3000/users',
params: {
username: username,
password: password
}
});
}
register(name, age, email, username, password) {
return this.$http({
method: 'POST',
url: 'http://localhost:3000/users',
data: {
name: name,
age: age,
email: email,
username: username,
password: password
}
});
}
// SHOULD I PUT HERE THE USERNAME EXIST VALIDATION LOGIC ?
}
<div class="container main-content">
<form class="registrationForm" name="registerForm" ng-submit="register.onSubmit(register.user)" novalidate="novalidate">
<!-- Enter Name -->
<div class="form-group">
<label for="name" class="control-label"><span id="reqInfo">*</span> Name</label>
<input type="text" name="name" class="form-control" ng-model="register.user.name" ng-pattern="/[a-zA-Zа-яА-Я]+/" id="name"
required="" placeholder="Example: Petar Petrov">
<div ng-messages="registerForm.name.$error" ng-show="registerForm.name.$touched" style="color:maroon" role="alert">
<div ng-message="required">Your name is required</div>
</div>
</div>
<!-- User Age-->
<div class="form-group">
<label for="age" class="control-label"><span id="reqInfo">*</span> Age</label>
<input type="number" name="age" class="form-control" ng-model="register.user.age" ng-min="18" min="18" id="age" required=""
placeholder="Enter your age">
<div ng-messages="registerForm.age.$error" ng-show="registerForm.age.$touched" style="color:maroon" role="alert">
<div ng-message="min">You must be at leats 18 years old</div>
</div>
</div>
<!-- Enter E-mail -->
<div class="form-group">
<label for="email" class="control-label"><span id="reqInfo">*</span> E-mail</label>
<input type="email" name="email" class="form-control" ng-model="register.user.email" ng-pattern="/((([A-Za-z]{3,9}:(?:\/\/)?)(?:[\-;:&=\+\$,\w]+#)?[A-Za-z0-9\.\-]+|(?:www\.|[\-;:&=\+\$,\w]+#)[A-Za-z0-9\.\-]+)((?:\/[\+~%\/\.\w\-_]*)?\??(?:[\-\+=&;%#\.\w_]*)#?(?:[\.\!\/\\\w]*))?)/"
id="email" required="" placeholder="Example: mail#mail.net">
<div ng-messages="registerForm.email.$error" ng-show="registerForm.email.$touched" style="color:maroon" role="alert">
<div ng-message="required">Your valid e-mail is required</div>
</div>
<br>
<!-- Enter Username -->
<div class="form-group">
<label for="username" class="control-label"><span id="reqInfo">*</span> Username</label>
<input type="text" name="username" ng-minlength="5" ng-maxlength="20" class="form-control" ng-model="register.user.username"
ng-pattern="/^[A-Za-z0-9_]{1,32}$/" ng-minlength="7" id="username" required="" placeholder="Enter your username">
<div ng-messages="registerForm.username.$error" style="color:maroon" role="alert">
<div ng-message="minlength">Your Username must be between 7 and 20 characters long</div>
</div>
<br>
<!-- Enter Password -->
<div class="form-group">
<label for="password" class="control-label"><span id="reqInfo">*</span> Password</label>
<input type="password" name="password" class="form-control" ng-model="register.user.password" ng-minlength="7" id="password"
required="" placeholder="Enter your password">
<div ng-messages="registerForm.password.$error" style="color:maroon" role="alert">
<div ng-message="minlength">You Password must be at least 7 symbols long</div>
</div>
</div>
<!-- Register button -->
<div class="form-group">
<button class="btn btn-primary" type="submit" ng-disabled="!registerForm.name.$valid || !registerForm.age.$valid || !registerForm.email.$valid || !registerForm.username.$valid || !registerForm.password.$valid">Register</button>
</div>
<p>Fields with <span id="reqInfo">*</span> must be filled.</p>
</form>
</div>
Important is to know that I have being told explicitly to write it in ES6.
I have problem with the logic so look at my code and please fill it for me so I can use it and most important - learn it :S
Thank you so so much in advance!
I have implemented a directive for different kind of validations (sync Async), and it supports warning as well.
You may check it from
`https://plnkr.co/2WQHOo`
If this is what you needed and need more information, let me know I will try my best to answer.
I'm trying to build a donation form using angular-payments and sending the data to an Expressjs server.
Currently I'm having trouble getting my form to post data other than the data that angular-payments sends. How can a post data that's not part of the angular-payments scope using the same controller?
Here is my Angular script:
angular.module('donate', ['angularPayments'])
function DonateCtrl($scope, $http) {
$scope.handleStripe = function(status, response){
console.log('response', status, response);
if(response.error) {
console.log('error');
// there was an error. Fix it.
} else {
// got stripe token, now charge it or smt
console.log('no error');
var token = response.id;
console.log(token);
return $http.post('http://localhost:8181/api/payments', response)
}
}
};
And here's the HTML:
<form stripe-form="handleStripe" name="donateForm">
<h3>Credit Card Details</h3>
<label for="">Card number</label>
<input type="text" name="number" ng-model="number" payments-validate="card" payments-format="card" payments-type-model="type" ng-class="donateForm.number.$card.type" placeholder="4500 0000 0000 0000" />
<label for="">Expiry</label>
<input type="text" ng-model="expiry" payments-validate="expiry" payments-format="expiry" placeholder="01 / 99" />
<label for="">CVC</label>
<input type="text" ng-model="cvc" payments-validate="cvc" payments-format="cvc" payments-type-model="type" placeholder="123" />
<h3>Donor Details</h3>
<label for="name">Name on card </label>
<input type="text" name="name" ng-model="name" placeholder="John Smith">
<label for="address">Street Address</label>
<input type="text" name="address" ng-model="addressLine1" placeholder="123 Any Street" required/>
<input type="text" name="city" ng-model="addressCity" placeholder="Anytown" required />
<input type="text" name="province" ng-model="addressState" placeholder="Any Province" ng-required="addressCountry == 'Canada' || addressCountry == 'United States'" />
<select data-placeholder="Choose a Country" name="country" ng-model="addressCountry" required>
{% include 'includes/countryselect' %}
</select>
<input type="text" name="postcode" ng-model="addressZip" placeholder="A1B 2C3" ng-required="addressCountry == 'Canada' || addressCountry == 'United States'" />
<div ng-show="donateForm.addressLine1.$pristine && donateForm.addressLine1.$invalid || donateForm.addressCity.$pristine && donateForm.addressCity.$invalid || donateForm.addressState.$pristine && donateForm.addressState.$invalid || addressCountry.$pristine && addressCountry.$invalid || donateForm.addressZip.$pristine && donateForm.addressZip.$invalid" class="help-block">Enter your full home address.</div>
<label for="phone">Phone Number <small>(include country & area code)</small></label>
<input type="tel" name="phone" ng-model="phone" placeholder="+1 204-555-5555" required />
<div ng-show="donateForm.phone.$invalid && donateForm.phone.$pristine" class="help-block">Enter your phone number.</div>
<label for="email">Email Address</label>
<input type="email" name="email" ng-model="email" placeholder="johnsmith#email.com" required />
<div ng-show="donateForm.email.$invalid && donateForm.email.$pristine" class="help-block">Enter your email address.</div>
<button type="submit">Submit</button>
When you say post additional data, do you mean send data with the POST request?
This is how I do it as an example:
$http({
url: 'http://localhost:8181/api/payments',
method: 'POST',
data: {
key: value,
key2: value
}).success(function(data) {
// If successful
}).error(function(data) {
// If error
return data.message;
});