During registration, I am validating the user input; however, I don't know how to check if the user email exist already in the database.
What I want to do is the following: if the users email already exist then it will show a toast which says "email already exist" and if the user clicks register then it will not register and display the toast.
Here is the code:
Vue.js
data() {
return {
validate: false,
loading: false,
cpass: null,
dialog: {
success: false
},
rules: {
password: [v => v === this.form.pass || 'Passwords do not match.',
v => !!v || 'This field cannot be blank.'
]
},
form: {}
}
},
methods: {
submitRegistration() {
if (this.$refs.registration.validate()) {
let formData = new FormData()
formData.set('type', 'customer')
formData.set('email', this.form.email);
formData.set('pass', this.form.pass);
formData.set('fname', this.form.fname);
formData.set('lname', this.form.lname);
formData.set('address', this.form.address);
formData.set('city', this.form.city);
formData.set('province', this.form.province);
formData.set('contact', this.form.contact);
axios.post('./sql/registration.php', formData)
.then(() => {
this.dialog.success = true
}).catch((error) => {
console.error(error)
})
}
},
},
template: `<v-container>
<v-card elevation="0">
<v-card-title class="display-1 font-weight-light">Customer Registration</v-card-title>
<v-divider class="mx-4"/>
<v-card-text>
<v-row>
<v-col cols="12" sm="6" md="8">
<v-form ref="registration" v-model="validate">
<v-row>
<v-col cols="12" md="4"><v-text-field :rules="$rules.required" type="email" v-model="form.email" rounded filled placeholder="Email Address"/></v-col>
<v-col cols="12" md="4"><v-text-field :rules="$rules.required" v-model="form.pass" type="password" rounded filled placeholder="Password"/></v-col>
<v-col cols="12" md="4"><v-text-field :rules="rules.password" v-model="cpass" type="password" rounded filled placeholder="Confirm Password"/></v-col>
<v-col cols="12" md="6"><v-text-field :rules="$rules.required" v-model="form.fname" rounded filled placeholder="First Name"/></v-col>
<v-col cols="12" md="6"><v-text-field :rules="$rules.required" v-model="form.lname" rounded filled placeholder="Last Name"/></v-col>
<v-col cols="12"><v-text-field :rules="$rules.required" v-model="form.address" rounded filled placeholder="Home Address"/></v-col>
<v-col cols="12" md="4"><v-text-field :rules="$rules.required" v-model="form.city" rounded filled placeholder="City"/></v-col>
<v-col cols="12" md="4"><v-select :rules="$rules.required" :items="$provinces" v-model="form.province" rounded filled placeholder="Province"/></v-col>
<v-col cols="12" md="4"><v-text-field v-model="form.contact" maxlength="11" rounded filled placeholder="Contact No." hint="e.g. 09021231234"/></v-col>
<v-col cols="12" align="end"><v-btn :loading="loading" #click="submitRegistration" large depressed rounded color="primary">Sign Up Now</v-btn></v-col>
</v-row>
</v-form>
</v-col>
<v-col cols="12" sm="6" md="4">
<transition appear name="slide-fade">
<v-img height="100%" src="assets/img/customer-reg.jpg" style="border-radius: 25px;"/>
</transition>
</v-col>
</v-row>
</v-card-text>
</v-card>
<v-dialog v-model="dialog.success" max-width="480">
<v-card>
<v-card-title>Registration Complete!</v-card-title>
<v-card-text>Welcome! Thank you for registering an account at our shop. You can now order apparel from any of our sellers.</v-card-text>
<v-card-actions>
<v-btn x-large tile depressed block color="primary" to="/sign-in">Get Started</v-btn>
</v-card-actions>
</v-card>
</v-dialog>
</v-container>`
})
php:
$type = $_POST['type'];
$password = password_hash($_POST['pass'], PASSWORD_DEFAULT);
$form = array($type, $_POST['fname'], $_POST['lname'], $_POST['address'], $_POST['city'], $_POST['province'], $_POST['contact'], $_POST['email'], $password);
$sql = $handler->prepare('INSERT INTO accounts(type, fname,lname,address,city,province,contact,email,password) VALUES(?,?,?,?,?,?,?,?,?)');
$sql->execute($form);
break;
Thank you.
Best practice is to validate the email while filling the form itself by using #keyup, #blur or #change event as per the requirement. For Demo, I am using #keyup event to validate the email address.
Demo :
new Vue({
el: '#app',
data: {
form: {
email: null
},
emailMessage: ''
},
methods: {
validateEmailAddress() {
if (!this.form.email) {
this.emailMessage = ''
return;
}
// API call will be happen here to validate the entered email address.
// For now i am just using mock response (assume you are getting this list from API or you can also get the boolean value) for the demo.
const response = ['abc#gmail.com', 'def#gmail.com', 'alpha#gmail.com', 'beta#gmail.com'];
this.emailMessage = (response.includes(this.form.email)) ? 'Email already exist' : 'Hurray! Good to Go';
}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<input type="email" v-model="form.email" placeholder="Email Address" #keyup="validateEmailAddress"/>
<p>{{ emailMessage }}</p>
</div>
You can do it in multiple ways. One way is to call a function on email input event, so that each time the user enters a character an endpoint is called to check if the email is already available.
<v-text-field type="email" v-model="form.email" placeholder="Email Address" #input="debouceCheckEmail" />
PS. You can use lodash to debounce endpoint calls to database.
import { debounce } from 'lodash';
export default {
methods: {
debouceCheckEmail() {
debounce(function () {
//check entry in database
}, 500);
}
}
}
Related
I am struggling to find out why it's able to send some data but not others. It submits 'email' and 'password' and 'id'... and just doesn't post 'sex' and 'dob'... I've been staring at it for the past several days.
function doPost(e){ //this doPost(e) function on my app script app is able to allow interaction between my php and my app script app
var error = null;
if(typeof e.parameter.action == 'undefined'){
error = "action parameter required";
}
else if(e.parameter.action == "CRUD"){ //CREATE RECORD PROCCESS - the updateRecord() function is able to create record on a row with corresponding email.
var result = updateRecord(e.parameter.email.trim(), e.parameter.password.trim(), e.parameter.id.trim(), e.parameter.sex.trim(), e.parameter.date.trim(), e.parameter.dob.trim());
}
following is the function which is called by doPost(e) on my app script, and then proceeds to do Update or Create new record if an email does not exist... by basically appending to the spreadsheet.
function updateRecord(email, password, id, sex, date, dob) {
var sheet = SpreadsheetApp.getActiveSpreadsheet();
var mySheet = sheet.getSheetByName("profiledata");
var lastRow = mySheet.getLastRow();
var ar = [email,password,id,sex,date,dob];
var newRecord = [email,password,id,sex,date,dob];
var range = mySheet.getRange(2, 1, lastRow - 1);
var check = range.createTextFinder(email).findNext(); // this line of code checks the row and gets data by email
var status;
if (check) {
check.offset(0, 0, 1, ar.length).setValues([ar]);
// status = 'Record Updated';
return {
status: "success",
message: "Record Updated"
}
}
else {
range.offset(lastRow - 1, 0, 1, ar.length).setValues([newRecord]);
// status = 'New Record created';
return {
status: "success",
message: "New Record created"
}
}
}
Following is my PHP insert file... post.php... which is able to send form data toward the above doPost(e) function, which in turn runs updateRecord() function
$url = "App script URL "; //this is where I pasted the URL of my app script
$postData = [
"action" => "CRUD",
"email" => $_POST['email'],
"password" => $_POST['password'],
"id" => $_POST['id'], // "ignore this Comment!!" I create an id separately and echo it into the html form input as readonly.
"sex" => $_POST['sex'],
"date" => $_POST['date'],
"dob" => $_POST['dob'],
];
$ch = curl_init($url);
curl_setopt_array($ch, [
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POSTFIELDS => $postData
]);
$result = curl_exec($ch);
$result = json_decode($result, 1);
if($result['status'] == "success"){
$returnmsg = $result['message'];
$_SESSION['success'] = $returnmsg;
header("location: table.php?=success $returnmsg");
}else{
$_SESSION['error'] = $result['message'];
$errormsg = $result['message'];
header("location: table.php?=err$errormsg");
}
Below is my HTML form
<form method="post" action="post.php">
<div class="form-group">
<label for="exampleInputEmail1">Email address</label>
<input type="text" name="email" class="form-control" placeholder="Enter email" autocomplete="on">
</div>
<div class="form-group">
<label for="password">password Field</label>
<input type="password" name="password" class="form-control" placeholder="this is a place for password" autocomplete="on">
</div>
<div class="form-group">
<label for="id">id Field</label>
<input type="text" name="id" class="form-control" value="<?php echo $id;?>" readonly>
</div>
<div class="form-group">
<label for="sex"> Gender Field</label>
<input type="text" name="sex" class="form-control" placeholder="this is a place for gender" autocomplete="on">
</div>
<div class="form-group">
<label for="dob">Date of Birth Field</label>
<input type="text" name="dob" class="form-control" placeholder="this is a place for DOB" autocomplete="on">
</div>
<button type="submit" name="submit" class="btn btn-primary">Submit</button>
</form>
my problem is that this process is only able to send data to the spreadsheet but only up to 'id'... it doesn't submit 'sex' and 'date'
I searched all over google's documentation, and other places, I am coming up with nothing...
I have a problem I tried many things but is doesn't fixed so please I need your help
this is my Vue Temp:
<form #submit.prevent="createCat" enctype="multipart/form-data" method="POST">
<div class="mt-1 relative rounded-md shadow-sm mb-3">
<input id="cat_name" type="text" v-model="categories.cat_name" />
</div>
<div class="mt-1 relative rounded-md shadow-sm mb-3 w-50">
<input name="img_url" id="img_url" accept="image/*" type="file">
</div>
<button type="submit">Add</button>
</form>
data(){
return{
categories:{
cat_name: '',
img_url: null,
},
}
},
methods:{
createCat(){
let data = new FormData();
data.append('cat_name', this.categories.cat_name);
data.append('url', this.categories.img_url);
this.$inertia.post('/categories', this.categories)
.then(()=>{
//
})
},
}
and in the Controller I tried debug the requests but it always return NULL
public function store(Request $request)
{
dump($request->file('img_url'));
dump($request->cat_name);
dump($request->all());
}
The Result
null
"name"
array:2 [▼
"cat_name" => "name"
"img_url" => null
]
As per official documentation
<template>
<form #submit.prevent="submit">
<input type="text" v-model="form.name" />
<input type="file" #input="form.avatar = $event.target.files[0]" />
<progress v-if="form.progress" :value="form.progress.percentage" max="100">
{{ form.progress.percentage }}%
</progress>
<button type="submit">Submit</button>
</form>
</template>
<script>
import { useForm } from '#inertiajs/inertia-vue3'
export default {
setup () {
const form = useForm({
name: null,
avatar: null,
})
function submit() {
form.post('/users')
}
return { form, submit }
},
}
</script>
Ref:https://inertiajs.com/file-uploads#form-data-conversion
i found the solution for this problem:
the input field must be like that:
<input name="img_url" id="img_url" type="file" #input="categories.img_url = $event.target.files[0]" />
Update
and I figure out that I have to change the variable name because I used the same variable for the props and the data variable that I want to store it and send it to backend, so I make the props from backend categories and the data that I want to store it category.
I am using a html form to get user data using laravel php. On form submit I am executing an api which in Web.php is defined as
Route::post('/register_user', 'UserRegistrationController#registerUser');
which executes,
public function registerUser(Request $request){
$apiResult = $this->executeApi($request->input('mobile_no'));
if($apiResult === "Success"){
return view('further_view');
}else{
toastr()->error('Registration Failed. Please check mobile number.');
return back();
}
}
html code
<div class="form-group{{ $errors->has('mobile_no') ? ' has-error' : '' }}">
<label for="mobile_no">Mobile No</label>
<input type="text" name="mobile_no" class="form-control" id="mobile_no" value="{{ old('mobile_no') }}" placeholder="Enter Mobile No" required>
<small class="text-danger">{{ $errors->first('mobile_no') }}</small>
</div>
My issue here is , whenever my $apiResult === "Success" condition goes false, i get toast message on screen but my page get refreshed and all the data user has typed gets cleared from the input box.
Hence my question is how can I show the toast messages without form being cleared or how would I prevent the input box getting cleared on such conditions.
I am using this Toast library
https://github.com/yoeunes/toastr
I would suggest that you use a session to store the data. For example:
session()->put('forms.mobile_no', $request->get('mobile_no'));
Your HTML:
<input value="{{ $mobile_no }}" type="text" name="mobile_no" class="form-control" id="mobile_no" placeholder="Enter Mobile No" required>
Try to return the error message back with this after the toastr call:
return redirect->back()->withInput();
I want to remove email field from checkout page for guest, I use OpenCart 3 with theme Journal 3. So what I can do?
I've tried to call out it from guest.php but still not work.
You can't just remove email field. A lot of system properties connected to email on checkout, although using journal3 makes more complicated extraction of email.
You can see what fields you can turn on / switch of in Journal Quick Checkout:
Journal > Skins > Checkout
UPDATED
To disable Email only for guests in Journal 3 Quick Checkout:
Go to /catalog/view/theme/journal3/template/journal3/checkout/register.twig
Find
{# customer email #}
<div class="form-group required account-email">
<label class="control-label" for="input-email">{{ entry_email }}</label>
<input v-model="order_data.email" type="text" name="email" value="" placeholder="{{ entry_email }}" id="input-email" class="form-control"/>
<span class="text-danger" v-if="error && error.email" v-html="error.email"></span>
</div>
Adding a check, like for password v-if="account === 'register'". New code is
{# customer email #}
<div v-if="account === 'register'" class="form-group required account-email">
<label class="control-label" for="input-email">{{ entry_email }}</label>
<input v-model="order_data.email" type="text" name="email" value="" placeholder="{{ entry_email }}" id="input-email" class="form-control"/>
<span class="text-danger" v-if="error && error.email" v-html="error.email"></span>
</div>
Now go to /catalog/controller/journal3/checkout.php and find
// email
if ((utf8_strlen(Arr::get($this->request->post, 'order_data.email')) > 96) || !filter_var(Arr::get($this->request->post, 'order_data.email'), FILTER_VALIDATE_EMAIL)) {
$error['email'] = $this->language->get('error_email');
} else if (($this->session->data['account'] === 'register') && $this->model_account_customer->getTotalCustomersByEmail(Arr::get($this->request->post, 'order_data.email'))) {
$error['email'] = $this->language->get('error_exists');
}
Replace with
// email
if ($this->session->data['account'] === 'register') {
if ((utf8_strlen(Arr::get($this->request->post, 'order_data.email')) > 96) || !filter_var(Arr::get($this->request->post, 'order_data.email'), FILTER_VALIDATE_EMAIL)) {
$error['email'] = $this->language->get('error_email');
} else if (($this->session->data['account'] === 'register') && $this->model_account_customer->getTotalCustomersByEmail(Arr::get($this->request->post, 'order_data.email'))) {
$error['email'] = $this->language->get('error_exists');
}
}
Additional to the emntioned 3 steps you have to fix the sendmail funtion. One way is mentioned here in 2 more steps:
File: system/library/mail.php
Change:
$this->to = $to;
To:
if ($to != '') {$this->to = $to;} else { $this->to = 'web-and-seo#itech.bg';}
Change web-and-seo#itech.bg to an e-mail that you will receive the confirmation instead of the customer.
Then remove the * from the mail field on checkout page
File: catalog/view/theme/journal3/template/journal3/checkout/register.twig
Change:
<div class="form-group required account-email">
To:
<div class="form-group account-email">
Good luck.
I've spent hours searching SO for this, but I wasn't able to find anyone who was trying to do what I was.
I'm trying to use http.post to send (an array of) data from an HTML form through Angular to PHP. When I try to do this, it sends the hardcoded values in the PHP file to PostgreSQL fine, but I'm not sure if Angular is sending the data to PHP or if I'm not accessing the $_POST variable correctly.
This is the code I have for this right now:
register-form.component.html:
<div class="container">
<h1>Sign Up</h1>
<h5>Items marked with a * are required.</h5> <br>
<form (ngSubmit)="onSubmit(model)" #registerForm="ngForm">
<div class="form-group">
<label for="username">Username *</label>
<input type="text" class="form-control width" id="username" required [(ngModel)]="model.username" name="account[username]"
#username = "ngModel">
<div [hidden]="username.valid || username.untouched" class="alert alert-danger">
Username is required
</div>
</div>
<div class="form-group">
<label for="password">Password *</label>
<input type="text" class="form-control width" id="password" minlength="6" required [(ngModel)]="model.password"
name="account[password]" #password = "ngModel">
<div [hidden]="password.valid || password.untouched" class="alert alert-danger">
Password is required and must be at least 6 characters
</div>
</div>
<div class="form-group">
<label for="email">E-mail *</label>
<input type="text" class="form-control width" id="email" required [(ngModel)]="model.email" name="account[email]"
#email = "ngModel" pattern="^([a-zA-Z0-9_\-\.]+)#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$">
<div [hidden]="!email.hasError('pattern') || email.untouched" class="alert alert-danger">
E-mail is required and must be a valid e-mail
</div>
</div>
<div class="form-group">
<label for="phoneNumber">Phone Number</label>
<input type="text" pattern="[0-9]*" class="form-control width" minlength="10" maxlength="10" id="phoneNumber"
name="account[phone]" [(ngModel)]="model.phoneNumber" #number = "ngModel">
<div [hidden]="number.pristine">
<div [hidden]="!number.hasError('minlength')" class="alert alert-danger">Phone number should only have 10 digits in xxxxxxxxxx format.</div>
<div [hidden]="!number.hasError('pattern')" class="alert alert-danger">Phone number should only have digits.</div>
</div>
</div>
<input type="submit" class="btn btn-success"[disabled]="!registerForm.form.valid" value="Submit">
</form>
</div>
register-form.component.ts:
import { Component, OnInit } from '#angular/core';
import { user } from '../user';
import { Http, HttpModule, Response } from '#angular/http';
import { HttpClient } from '#angular/common/http';
#Component({
selector: 'app-register-form',
templateUrl: './register-form.component.html',
styleUrls: ['./register-form.component.css']
})
export class RegisterFormComponent implements OnInit {
constructor(private http: Http) { }
model = new user('','','','');
ngOnInit() { }
submitted = false;
onSubmit(...event: user[]) {
this.submitted = true;
console.log(event); //just for testing - outputs inputted data from form into console
console.log(event[0]); //same as above
var test = this.http.post('http://localhost/register-form-component.php', event[0]); //should this just be 'event'?
test.subscribe();
}
}
register-form-component.php:
<?php
$dbconn = pg_connect("host=localhost port=5432 dbname=sample user=sample password=sample");
if(!$dbconn) {
echo "connection failed";
exit;
}
$test = ["testuser","testpass132","example#gmail.com",1234566543];
$values = [$_POST['username'], $_POST['password'], $_POST['email'], $_POST['phoneNumber']];
$result = pg_prepare($dbconn, "insert_accounts", 'INSERT INTO accounts (username, password, email, phone_number) VALUES ($1,$2,$3,$4)');
$result = pg_execute($dbconn, "insert_accounts", $test); //this works
$result = pg_execute($dbconn, "insert_accounts", $values); //the data table in PGAdmin skips a primary key every time this file runs; it is because of this line (see edit below).
if (!$result) {
echo "An INSERT query error occurred.\n";
exit;
}
pg_close($dbconn);
?>
Thanks!
EDIT: This wasn't showing up before, but when I open up localhost/register-form-component.php, it gives the following output:
Array
Warning: pg_execute(): Query failed: ERROR: null value in column "username" violates not-null constraint DETAIL: Failing row contains (31, null, null, null, null). in /Library/WebServer/Documents/register-form-component.php on line 16
An INSERT query error occurred.
I assume this means that $_POST contains [null, null, null, null].
This same error shows up when event[0] is changed to event in the http.post().
EDIT 2:
First output is of console.log(event), second is of console.log(event[0])
EDIT 3:
This is what shows up in the network tag after submitting the form
EDIT 4:
In the header tab under network, it shows this.
It turns out that the reason why PHP was showing $_POST as containing null values is because it was empty, as I had not declared what was to be in it. Using the method in Mike Brant's answer, I added the following lines to my code:
$postdata = file_get_contents("php://input");
$request = json_decode($postdata);
$username = $request->username;
$password = $request->password;
$email = $request->email;
$phoneNumber = $request->phoneNumber;
And it worked! Thank you Jaime for patiently abiding by all of my questions.