Password confirmation(form validation) from server-side to client side - javascript

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);

Related

Required attribute is not working in registration form

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

redirecting user to different page after pressing submit using vue.js

I am trying to redirect a user to a different page after they input there correct user information and then pressing the submit button using (window.location.href) to redirect but the page keeps reloading after the form has been submitted
<form id="login" method="post">
<h1>Login students</h1>
<label for ="username">username:</label>
<input required type="username" id="username" v-model="username">
<br><br>
<label for="password">password: </label>
<input required type="password" id="password" v-model='password'>
<br><br>
<button v-on:click='onSubmit'>submit</button>
</form>
var loginApp = new Vue({
el: '#login',
data: {
username: '',
password: '',
},
methods: {
onSubmit: function () {
// check if the email already exists
var users = '';
var newUser = this.username;
var passcheck = this.password;
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 & user.password === passcheck
})) {
//alert('Welcome back-' + newUser);
//window.location.href = '<index.html>' + '' + newUser;
window.location.href = "index.html";
} else {
alert('Incorrect username or password');
}
}
}
}
});
the proble is with
<form id="login" method="post">
the form doesn't have an action defined, so it makes the browsers refresh.
you need to prevent the default action either through the form element
<form v-on:submit.prevent>
or through your onsubmit handler:
methods: {
onSubmit: function (e) {
e.preventDefault()
//...
}
}

Angular JS to validate Log in Information

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!')
}
}
}
});

Registering new login Information Angular JS

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)
}
});

Validate form fields using ajax

I do have a jquery code to validate my form but unfornutately it is not that accurate. I would like to validate the fields thoroughly like only to accept numbers on phone field and only a valid email address on email field.
Also I would like to show the error ( or just add a red border one field ) as soon as the user types/inputs a value without clicking submit button, so it looks like a real time checker.
Can anyone derive my script, I am really not confident about this. Also derive my php code if u think it is wrong. Would love to learn how to use session also so user can only submit once every session.
Code:
<head>
<script>
$(function () {
$('.cbf').on('submit', function (e) {
e.preventDefault();
var name = $('#name').val();
var phone = $('#phone').val();
var email = $('#email').val();
if ( name == "" ) {
alert('Please provide valid name');
$('#name').addClass('error');
}
else if ( phone == "" ) {
alert('Please provide a valid phone number');
$('#phone').addClass('error');
$('#name').removeClass('error');
}
else if ( email == "" ) {
alert('Please provide a valid email');
$('#email').addClass('error');
$('#phone').removeClass('error');
}
else {
$.ajax({
type: 'post',
url: 'index.php',
data: $('.cbf').serialize(),
data: "name="+ name +"& phone="+ phone +"& email="+ email,
success: function () {
alert('We will contact you shortly! Thanks!');
},
complete:function(){
$('.cbf').each(function(){
this.reset(); //Here form fields will be cleared.
});
}
});
$('#email').removeClass('error');
}
});
});
</script>
</head>
<form method="post" action="<?php echo $_SERVER["PHP_SELF"];?>" class="cbf">
<fieldset>
<input type="text" id="name" name="name" value="" placeholder="Name">
<input type="text" id="phone" name="phone" value="" placeholder="Phone">
<input type="email" id="email" name="email" value="" placeholder="Email Address">
<input type="submit" id="submit" name="submit" value="Get Call Back">
</fieldset>
</form>
<?php
session_start();
if ('POST' === $_SERVER['REQUEST_METHOD']) {
$_SESSION['posted'] = true;
$to = "myemail#gmail.com";
$subject = "Someone wants a Call Back!";
// data the visitor provided
//$name_field = $_POST['name'];
//$phone_field = $_POST['phone'];
//$email_field = $_POST['email'];
$name_field = filter_var($_POST['name'], FILTER_SANITIZE_STRING);
$email_field = filter_var($_POST['email'], FILTER_VALIDATE_EMAIL);
$phone = filter_var($_POST['phone'], FILTER_SANITIZE_INT);
//constructing the message
$body = " From: $name_field\n\n Phone: $phone_field\n\n E-mail: $email_field\n\n";
// ...and away we go!
mail($to, $subject, $body);
} else {
// handle the error somehow
}
?>
Try this code :
$("#signupform").validate({
rules: {
email: {
required: true,
email: true
},
mobile: {
required: true,
number: true,
minlength: 10,
maxlength: 10
}
},
messages: {
email: {
required: "Please enter a valid email address.",
email: "Invalid Email Address."
},
mobile: {
required: "Please provide a mobile number.",
minlength: "Your mobile number must be 10 characters long.",
maxlength: "Your mobile number must be 10 characters long.",
number: "Please Enter number only."
}
}
});
Its better to validate on both server side and client side. Client side validate then display the error to user. On server side, you need to validate again, just because your JS code can be changed by malicious user.
A simple example with phone.
//client side
var phone = $('#phone').val();
//validate
if(/^\d+$/.test(phone) === false){ //not number
alert('Your phone number is not valid');
}
//on server side
$phone = $_POST['phone'];
if(is_numeric($phone)){
insert $phone into database.
}
Another way is to use HTML5 and new tags like : "email" and "tel" (tel is not supported for the moment) :
<input type="tel" name="phone" required>
and for email :
<input type="email" name="email" required>
Even the solution you choose, you have to do a control on the server side in Php for your case.
It's not the solution but in the futur, I think we should use these tags.
More informations : http://www.w3schools.com/html/html5_form_input_types.asp
Here is a simple jQuery validation:
The form:
<form id="myform">
email<input type="text" name="field1" />
<br/>
password<input type="text" name="field2" />
<br/>
<input type="submit" />
</form>
The validation part
$(document).ready(function () {
$('#myform').validate({ // initialize the plugin
rules: {
field1: {
required: true,
email: true
},
field2: {
required: true,
minlength: 5
}
},
submitHandler: function (form) { // for demo
alert('valid form submitted'); // for demo
return false; // for demo
}
});
});
http://jsfiddle.net/VuPPy/

Categories