Textbox unique value in Laravel,vuejs,Axios, JavaScript - javascript

I want to be displayed the toastr popup message when the user try to insert the duplicate value for BageCode in form the if anyone can help me it will be so kind of him.
I the rest form column validation is working the toaster is working but I don't know how to compare the data from database and data in form
like this
if (this.form.BadgeCode == data.BadgeCode) {
toast.fire({
type: "warning",
title: "The badge code has already been taken."
});
}
Code in EmployeeController is:
public function index()
{
$date=\Carbon\Carbon::today();
// $this->authorize('isAdmin');
$employee=Employee::where('expiredate','>',$date)->paginate(5);
// return Employee::all();
return response()->json($employee);
}
public function store(Request $request)
{
// $this->authorize('isAdmin');
$this->validate($request,[
// 'BadgeCode'=>'required|string',
'BadgeCode'=>'required|unique:employees,BadgeCode',
'BadgeType'=>'required',
]) 'company_id'=>'required',
}
Code in api route is:
Route::apiResources(['employee'=>'API\EmployeeController']);
Code in Employee.vue is:
<div
style="width:45%;margin-left: 35%;"
class="modal fade"
id="addNew"
tabindex="-1"
role="dialog"
aria-labelledby="addNewLabel"
aria-hidden="true"
>
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" v-show="!editMode" id="addNewLabel">Add New employee</h5>
<h5 class="modal-title" v-show="editMode" id="addNewLabel">Update employee's Info</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<form
#submit.prevent="editMode ? updateemployee() : createemployee()"
enctype="multipart/form-data"
>
<div class="modal-body">
<div class="form-group">
<select
name="company_id"
id="company_id"
:class="{'is-invalid':form.errors.has('company_id')}"
class="form-control"
v-model="form.company_id"
>
<option value selected>Select Company</option>
<option
v-for="Company in Companies"
:key="Company.id"
:value="Company.id"
>{{Company.Company}}</option>
</select>
<has-error :form="form" field="company_id"></has-error>
</div>
<div class="form-group">
<input
v-model="form.BadgeCode"
placeholder="Enter BadgeCode"
type="text"
name="BadgeCode"
class="form-control"
/>
<!-- :class="{ 'is-invalid': form.errors.has('BadgeCode') }" -->
<!-- <has-error :form="form" field="BadgeCode"></has-error> -->
</div>
<div class="form-group">
<select
name="BadgeType"
v-model="form.BadgeType"
id="BadgeType"
class="form-control"
:class="{'is-invalid':form.errors.has('BadgeType')}"
>
<option value selected>Select BadgeType</option>
<option value="Resident">Resident</option>
<option value="Non-Resident-Expat">Non-Resident Expat</option>
<option value="Non-Resident-LN">Non-Resident LN</option>
<option value="Baron-employee">Baron-employee</option>
</select>
<has-error :form="form" field="BadgeType"></has-error>
</div>
</div>
</form>
</div>
</div>
</div>
Code in script is:
<script>
export default {
// el: "#wrapper2",
data() {
return {
seen: false,
seen2: true,
color: "blue",
size: "20px",
editMode: false,
Companies: {},
employees: {},
form: new Form({
id: "",
BadgeCode: "",
BadgeType: "",
company_id: "",
})
};
},
methods: {
getvalidateion() {
axios.get("api/employee").then(response => {
let data = response.data.data;
if (data) {
data.forEach(element => {
if (this.form.BadgeCode == data.BadgeCode) {
toast.fire({
type: "warning",
title: "The badge code has already been taken."
});
}
});
} else {
console.log("NO DATA");
}
});
},
createemployee() {
this.getvalidateion();
if (this.form.company_id == "") {
toast.fire({
type: "warning",
title: "Please Select the Company."
});
} else if (this.form.BadgeCode == "") {
toast.fire({
type: "warning",
title: "BadgeCode is required."
});
} else if (this.form.BadgeType == "") {
toast.fire({
type: "warning",
title: "Please Select the BadgeType."
});
} else if (this.form.nationality_id == "") {
toast.fire({
type: "warning",
title: "Please Select the Nationality."
});
} else if (this.form.expiredate == "" || this.form.issuedate == "") {
toast.fire({
type: "warning",
title: "Please fill the issuedate or expiredate fileds ."
});
} else if (this.form.photo.length == "") {
toast.fire({
type: "warning",
title: "Please select photo."
});
} else if (
this.form.afghanidatephoto != undefined &&
this.form.afghanidatephoto.length == ""
) {
toast.fire({
type: "warning",
title: "Please select AfghaniDate."
});
} else {
this.form
.post("api/employee")
.then(() => {
// the below function will be use to reload the page
// this.$emit("refreshPage");
$("#addNew").modal("hide");
toast.fire({
type: "success",
title: "employee Created successfully"
});
this.form.reset();
$("#afghanidatephoto").val("");
$("#photo").val("");
Fire.$emit("refreshPage");
})
.catch(e => {
console.log(e);
});
}
},
created() {
Fire.$on("searching", () => {
let query = this.$parent.search;
axios
.get("api/findemployee?q=" + query)
.then(data => {
this.employees = data.data;
})
.catch(() => {});
});
this.loademployees();
this.getvalidateion();
// load the page after 3 secound
Fire.$on("refreshPage", () => {
this.loademployees();
});
}
};
</script>
Code in Modal is:
$table->string('BadgeCode')->unique();

I found the solution instate of data.BadgeCode I should have put element.BadgeCode anyway thanks guys
getvalidateion() {
axios.get(this.url).then(response => {
let data = response.data;
//this.Companies != undefined && this.Companies.length == 0
if (data) {
data.forEach(element => {
this.employees2.push(element.BadgeCode);
if (this.form.BadgeCode == element.BadgeCode) {
toast.fire({
type: "warning",
title: "BadgeCode is already has been taken."
});
}
});
} else {
console.log("NO DATA");
}
});
}

Related

Vue form validation

I have some problems with mine Vue app.
I'm trying to validate login form that is connected with my Laravel App.
This is how template looks
<template>
<div>
<div class="main" v-if="canLogin">
<img class="logo" src="../assets/logo.png">
<form id="app"
#submit="checkForm"
method="post">
<p v-if="validation.length">
<b>Please correct the following error(s):</b>
<ul>
<li v-for="validation in validation">{{ error }}</li>
</ul>
</p>
<input class="form-input" type="email" v-model="form.email" id="email" align="center" placeholder="eMail" required>
<input class="form-input" type="password" v-model="form.password" id="password" align="center" placeholder="Password" required>
<button #click.prevent="login" class="submit">Sign In</button>
</form>
</div>
<div class="main" v-if="!canLogin">
<span> YOU ARE BLOCKED FOR 15 MINUTES</span>
</div>
</div>
</template>
As you see I want to foreach errors, but it's always giving error that
'validation' is defined but never used
And this is how mine script looks.
<script>
import User from "../apis/User";
export default {
data() {
return {
form: {
email: "",
password: ""
},
validation: [],
errors: '',
message: '',
canLogin: true,
};
},
mounted() {
User.canLogin().then(response => {
this.canLogin = response.data.canLogin;
});
},
methods: {
checkForm: function (e) {
this.errors = [];
if (!this.form.password) {
this.errors.push("Name required.");
}
if (!this.form.email) {
this.errors.push('Email required.');
} else if (!this.validEmail(this.email)) {
this.errors.push('Valid email required.');
}
if (!this.errors.length) {
return true;
}
e.preventDefault();
},
validEmail: function (email) {
var re = /^(([^<>()[\]\\.,;:\s#"]+(\.[^<>()[\]\\.,;:\s#"]+)*)|(".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(email);
},
login() {
User.login(this.form)
.then(response => {
this.$store.commit("LOGIN", true);
localStorage.setItem("token", response.data.token);
this.$router.push({ name: "Dashboard" });
this.$snotify.success(response.data.message, {
timeout: 2000,
showProgressBar: true,
closeOnClick: true,
pauseOnHover: true
});
})
.catch(error => {
if (error.response.status === 400) {
this.errors = error.response.data.message;
this.$snotify.error(error.response.data.message, {
timeout: 2000,
showProgressBar: true,
closeOnClick: true,
pauseOnHover: true
});
}
if(error.response.status === 429){
this.canLogin = false;
}
});
}
}
};
</script>
I'm catching few thhings, like, canLogin, this is checking if IP is not blocked.
There is one more error like:
Elements in iteration expect to have 'v-bind:key' directives
I'm just a started with vue so don't judge me if it's simple fix.
BTW: without validation works fine, I believe it's not only problem with those errors and probbly I'm not catching some things as needed.
What am I doing wrong here?
Change
<ul>
<li v-for="validation in validation">{{ error }}</li>
</ul>
To:
<ul>
<li v-for="(error,index) in errors" v-bind:key="index">{{ error }}</li>
</ul>
In vue, you must provide a key for every v-for looping.
And change your data to:
data() {
return {
form: {
email: "",
password: ""
},
validation: [],
errors: [],
message: '',
canLogin: true,
};
},
I made your errors variable an arrayList.

promise and jquery validation are not working

As you can see below, I have a modal that should be validated then send a request to the server. The problem is that if I try to submit for the first time, that validation is worked properly but for the second time it won't work. When I debug the codes I found out that validationCheck() worked fine but the resolve() doesn't return any result to the add() in certificate-manager file.
request.js
let insert = function (isPost = false, url, data, reloadLocation = false, table = null,
modal = null, ponds) {
let request = null;
if (isPost) {
let uploadNotify = uploadNotification();
//step 3
let config = {
onUploadProgress: function (progressEvent) {
let percentCompleted = Math.round((progressEvent.loaded * 100) / progressEvent.total);
console.log(percentCompleted);
uploadNotify.update('message', '<strong>Uploading</strong> ' + percentCompleted + ' %');
uploadNotify.update('progress', percentCompleted);
},
headers: {
'content-type': 'multipart/form-data'
}
};
//step 4
request = axios.post(url, data, config)
} else {
//step 4
request = axios.get(url, {
params: data
});
}
request.then(function (response) {
console.log(response);
let data = response['data'];
if (data['status'] === 200) {
let content = {
'title': 'Done!',
'message': data['message']
};
notification(content, 1);
if (reloadLocation)
location.reload();
if (table) {
table.ajax.reload();
clearModal('.inp', ponds);
}
}
})
.catch(function (error) {
console.log(error);
let data = error['data'];
let content = {
'title': 'Error!',
'message': data['message']
};
notification(content, 0);
})
.then(function () {
if (modal)
closeModal(modal);
});
};
utilities.js
async function validationCheck (id, rules) {
jQuery.validator.addMethod('passwordCheck', function (value, element, param) {
//Your Validation Here
let oldPass = jQuery('#input-old-password').val();
let confirmPass = jQuery('#input-confirm-password').val();
return oldPass != null && confirmPass === value;
// return bool here if valid or not.
}, 'Your error message!');
jQuery.validator.addMethod('phoneNumber', function (value, element, param) {
value = value.replace(/\s+/g, "");
return this.optional(element) || value.length > 9 &&
value.match(/\(?([0-9]{3})\)?([ .-]?)([0-9]{3})\2([0-9]{4})/);
}, 'Please specify a valid phone number');
jQuery.validator.addMethod('startDate', function (value, element, param) {
return (parseInt(value) > 2000)
}, 'Please specify a valid year');
jQuery.validator.addMethod('endDate', function (value, element, param) {
return (parseInt(value) >= parseInt(jQuery('#input-start-time').val()) ||
jQuery('#input-current').is(":checked"))
}, 'Please specify a valid year');
jQuery.validator.addMethod('uendDate', function (value, element, param) {
return (parseInt(value) >= parseInt(jQuery('#input-update-start-time').val()) ||
jQuery('#input-update-current').is(":checked"))
}, 'Please specify a valid year');
return new Promise((resolve, reject)=> {
jQuery(id).validate({
// define validation rules
rules: rules,
errorPlacement: function (error, element) {
let group = element.closest('.input-group');
if (group.length) {
group.after(error.addClass('invalid-feedback'));
} else {
element.after(error.addClass('invalid-feedback'));
}
},
// messages: {
// username: {
// required: "Username is required"
// }
// },
//display error alert on form submit
invalidHandler: function (event, validator) {
// let alert = jQuery('#kt_form_1_msg');
// alert.removeClass('kt--hide').show();
KTUtil.scrollTo(id, -200);
reject(false);
},
submitHandler: function (form) {
resolve(true);
//form[0].submit(); // submit the form
}
});
});
}
certificate-manager.js
let add = async function () {
let check = await validationCheck("#form", {
title: {
required: true
},
company: {
required: true
},
start: {
required: true,
date: true,
digits: true,
minlength: 4,
maxlength: 4,
startDate: true
},
end: {
date: true,
digits: true,
minlength: 4,
maxlength: 4,
endDate: true
},
description: {
required: true
}
}).then(value => {
console.log(value)
insert(
false,
'/api/add/certificate',
getInputsData(),
false,
table,
"#kt_modal")
}, reason => {
console.log(reason)
}).catch(reason => {
console.log(reason)
});
}
<!--begin:: insert Modal-->
<div class="modal fade" id="kt_modal" tabindex="-1" role="dialog"
aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog modal-lg" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">New Certificate</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
</button>
</div>
<div class="modal-body">
<form id="form">
<div class="row">
<div class="col-12">
<div class="form-group">
<label for="input-title"
class="form-control-label">Title</label>
<input type="text" class="inp form-control"
name="title"
id="input-title">
</div>
<div class="form-group">
<label for="input-company-institute"
class="form-control-label">Company/Institute</label>
<input type="text" class="inp form-control" name="company" id="input-company-institute">
</div>
<div class="row">
<div class="form-group col-6">
<label for="input-start-time"
class="form-control-label">From Year</label>
<input type="text" class="inp form-control" name="start" id="input-start-time">
</div>
<div class="form-group col-6">
<label for="input-end-time"
class="form-control-label">To Year</label>
<input type="text" class="inp form-control" name="end" id="input-end-time">
<div class="mt-2">
<label for="input-current" class="kt-checkbox kt-checkbox--brand col-6">
<input type="checkbox" id="input-current"> Current
<span></span>
</label>
</div>
</div>
</div>
<div class="form-group">
<label for="input-description"
class="form-control-label">Description</label>
<textarea class="inp form-control" name = "description" id="input-description"></textarea>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button id="add-btn" onclick="add()" type="submit" class="btn btn-primary" >Submit</button>
</div>
</form>
</div>
</div>
</div>
</div>
<!--end::insert Modal-->
the order of the files is:
'../../../assets/adminPanel/js/utilities.js',
'../../../assets/adminPanel/js/request.js',
'../../../assets/adminPanel/js/pages/resume/certificate-manager.js'

Custom Validation Function not invoking

I have made and AngularJs app and made Form in HTML/CSS. The form takes 2 Dates. StartDate and endDate. For validations, I used the AngularJs Ng-messages. I created a custom validation function to check that endDate should not be before startDate. But the function is not invoking. Things i have checked.
Include Ng-messages file in start.
Add the function to Scope.
add the customer function name in input Tag of HTML.
Checked the spelling issue.
But nothing has worked for me. So, here I am to show it to you guys.
Layout = null;
}
<form name="newTenatForm" class="flex-fill" ng-submit="newTenatForm.$valid && onAddEditTenantSubmitForm(newTenatForm)" novalidate>
<div class="row">
<div class="col-lg-6 offset-lg-3">
<div class="card mb-0">
<div class="card-body">
<div class="text-center mb-3">
<i class="icon-stack icon-2x text-success border-success border-3 rounded-round p-3 mb-3 mt-1"></i>
<h5 class="mb-0">#ViewBag.title</h5>
<span class="d-block text-muted">Fields with * are required</span>
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group form-group-feedback form-group-feedback-right">
<input type="text" class="form-control" placeholder="Name *" name="tenantName" ng-minlength="5" ng-model="state.tenantModel.name" required>
<ng-messages class="form-text text-danger-400"
ng-if="newTenatForm.$submitted || newTenatForm.tenantName.$touched"
for="newTenatForm.tenantName.$error">
<div ng-message="minlength">Tenant name is too short.</div>
<div ng-message="required">Tenant name is required</div>
</ng-messages>
<div class="form-control-feedback">
<i class="icon-user-check text-muted"></i>
</div>
</div>
</div>
<div class="col-md-6">
<div class="form-group form-group-feedback form-group-feedback-right">
<input type="text" class="form-control" placeholder="Identifier *" name="tenantIdentifier" ng-minlength="5" ng-model="state.tenantModel.identifier" required>
<ng-messages class="form-text text-danger-400"
ng-if="newTenatForm.$submitted || newTenatForm.tenantIdentifier.$touched"
for="newTenatForm.tenantIdentifier.$error">
<div ng-message="minlength">Tenant Identifier is too short.</div>
<div ng-message="required">Tenant identifier is required</div>
</ng-messages>
<div class="form-control-feedback">
<i class="icon-user-check text-muted"></i>
</div>
</div>
</div>
</div>
<div class="form-group form-group-feedback form-group-feedback-right">
<input type="text" class="form-control" placeholder="Connection String" ng-model="state.tenantModel.connectionString">
<div class="form-control-feedback">
<i class="icon-user-plus text-muted"></i>
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group form-group-feedback form-group-feedback-right">
<input type="date" class="form-control" placeholder="Start Date" id="anytime-date" name="tenantStartDate" ng-model="state.tenantModel.startFrom" required>
<ng-messages class="form-text text-danger-400"
ng-if="newTenatForm.$submitted || newTenatForm.tenantStartDate.$touched"
for="newTenatForm.tenantStartDate.$error">
<div ng-message="required">Tenant start date is required</div>
</ng-messages>
<div class="form-control-feedback">
<i class="icon-user-lock text-muted"></i>
</div>
</div>
</div>
<div class="col-md-6">
<div class="form-group form-group-feedback form-group-feedback-right">
<input type="date" class="form-control" placeholder="End Date" id="tenantEndDate" name="tenantEndDate" ng-model="state.tenantModel.endOn" required compareWithStartDate>
<ng-messages class="form-text text-danger-400"
ng-if="newTenatForm.$submitted || newTenatForm.tenantEndDate.$touched"
for="newTenatForm.tenantEndDate.$error">
<div ng-message="required">Tenant end date is required</div>
<div ng-message="checkEndDate">End date cannot be before start date.</div>
</ng-messages>
<div class="form-control-feedback">
<i class="icon-user-lock text-muted"></i>
</div>
</div>
</div>
</div>
<div class="form-group form-group-feedback form-group-feedback-right">
<div class="form-group row">
<label class="col-form-label col-lg-2">Tenant Type *</label>
<div class="col-lg-10">
<select class="form-control" id="tenantType" name="tenantType" ng-model="state.tenantModel.tenantType" required>
<option value="1">Trial</option>
<option value="2">Standard</option>
</select>
<ng-messages class="form-text text-danger-400"
ng-if="newTenatForm.$submitted || newTenatForm.tenantType.$touched"
for="newTenatForm.tenantType.$error">
<div ng-message="required">Pleas select tenant type.</div>
</ng-messages>
</div>
</div>
</div>
<button type="submit" value="Submit" class="btn bg-teal-400 btn-labeled btn-labeled-right"><b><i class="icon-plus3"></i></b> #if (ViewBag.title == "Update Tenant")
{<span>Update Acccount</span> }
else
{ <span>Create account </span>} </button>
</div>
</div>
</div>
</div>
</form>```
and this is Js code.
```(function () {
var app = angular.module('app');
app.controller('MultiTenantController', ['$scope', '$window', '$filter', 'TenantServices', function ($scope, $window, $filter, TenantServices) {
var objectA = {}
var state = {
tenantModel: {
addedOn: '',
connectionString: '',
createdBy: '',
endOn: '',
id: '',
identifier: '',
isDisabled: '',
items: [{
isDisabled: '',
tenantType: '',
endOn: '',
startFrom: '',
}],
name: '',
startFrom: '',
tenantType: '',
userId: '',
},
};
var init = function (id) {
if (id) { tenantEdit(id); };
$(document).ready(function () {
tenantTable = $('#table_Tenants').DataTable({
ajax: {
url: 'API/MultiTenant/Pagged',
method: 'POST'
},
columns: [
{ data: 'name' },
{ data: 'identifier' },
{ data: 'connectionString' },
{
data: 'startFrom',
render: function (startFrom) {
return $filter('date')(startFrom, 'medium');
}
},
{
data: 'addedOn',
render: function (addedOn) {
return $filter('date')(addedOn, 'medium');
}
},
{
data: 'endOn',
render: function (endOn) {
return $filter('date')(endOn, 'medium');
}
},
{
data: 'isDisabled',
render: function (isDisabled) {
return !isDisabled ?'<span class="badge badge-success">Active</span>':'<span class="badge badge-danger">Inactive</span>';
}
},
{
data: function (data) {
return data;
},
orderable: false,
render: function (data) {
return `<div class="list-icons">
<div class="dropdown">
<a href="#" class="list-icons-item" data-toggle="dropdown">
<i class="icon-menu9"></i>
</a>
<div class="dropdown-menu dropdown-menu-right">
<i class="icon-database-upload"></i>Create Database
<i class="icon-database-edit2"></i>Edit
<i class="icon-database-remove"></i>Delete
</div>
</div>
</div>`;
}
},
]
});
tenantTable.on('click', '.createTenantDatabase', function () {
const $row = $(this).closest('tr');
const rowData = tenantTable.row($row).data();
addTenantDatabase(rowData);
});
tenantTable.on('click', '.deleteTenant', function () {
const $row = $(this).closest('tr');
const rowData = tenantTable.row($row).data();
deleteTenant(rowData);
});
})
};
const onAddEditTenantSubmitForm = function (newTenatForm) {
if (!state.tenantModel.userId) {
addTenant(newTenatForm);
}
else {
updateTenant(newTenatForm);
}
};
var addTenant = function (newTenatForm) {
state.isLoading = true;
TenantServices.addTenant(state.tenantModel).then(
function () {
swalInit.fire({
title: 'Success',
text: 'Tenant has been created',
type: 'success'
});
},
function (errorResponse) {
if (errorResponse.status === 400) {
swalInit.fire({
title: 'Server Error',
text: 'An server error occurred while adding tenant.',
type: 'error 400'
});
}
else if (errorResponse.status === 500) {
swalInit.fire({
title: 'Server Error',
text: 'An server error occurred while adding tenant.',
type: 'error 500'
});
}
}
)
.finally(() => state.isLoading = false);
};
var addTenantDatabase = function (rowObj) {
state.isLoading = true;
TenantServices.createTenantDatabase(rowObj.i).then(
function () {
swalInit.fire({
title: 'Success',
text: 'Tenant Database has been created',
type: 'success'
});
table_Tenants.ajax.reload();
},
function (errorResponse) {
if (errorResponse.status === 400) {
swalInit.fire({
title: 'Server Error',
text: 'An server error occurred while creating database tenant.',
type: 'error 400'
});
}
else if (errorResponse.status === 500) {
swalInit.fire({
title: 'Server Error',
text: 'An server error occurred while creating database tenant.',
type: 'error 500'
});
}
}
)
.finally(() => state.isLoading = false);
};
var updateTenant = function (rowObj) {
state.isLoading = true;
TenantServices.updateTenant(state.tenantModel).then(
function () {
swalInit.fire({
title: 'Success',
text: 'Tenant Updated!',
type: 'success'
});
tenantTable.ajax.reload();
},
function (errorResponse) {
if (errorResponse.status === 500) {
swalInit.fire({
title: 'Server Error',
text: 'An server error occurred while Updating Tenant.',
type: 'error'
});
}
else if (errorResponse.status === 404) {
swalInit.fire({
title: 'Server Error',
text: 'Tenant not found on Server.',
type: 'error'
});
}
}
)
.finally(() => state.isLoading = false);
};
var deleteTenant = function (rowObj) {
state.isLoading = true;
TenantServices.deleteTenant(rowObj.id).then(
function () {
swalInit.fire({
title: 'Success',
text: 'Tenant Deleted!',
type: 'success'
});
tenantTable.ajax.reload();
},
function (errorResponse) {
if (errorResponse.status === 500) {
swalInit.fire({
title: 'Server Error',
text: 'An server error occurred while Deleting Tenant.',
type: 'error'
});
}
else if (errorResponse.status === 404) {
swalInit.fire({
title: 'Server Error',
text: 'Tenant not found on Server.',
type: 'error'
});
}
}
)
.finally(() => state.isLoading = false);
};
var tenantEdit = function (id) {
TenantServices.getTenantById(id).then(function (data) {
var startDate = new Date(data.found.startFrom + "Z");
var endDate = new Date(data.found.endOn + "Z");
state.tenantModel = data.found;
state.tenantModel.startFrom = startDate;
state.tenantModel.endOn = endDate;
if(state.tenantModel.tenantType == 1)
{
$(function () {
$('#tenantType').val('1');
});
} else if (state.tenantModel.tenantType == 2)
{
$(function () {
$('#tenantType').val('2');
});
}
});
};
var compareWithStartDate = function () {
if (state.tenantModel.startFrom == state.tenantModel.endOn) {
newTenatForm.tenantEndDate.$setValidity('checkEndDate', true);
}
else {
newTenatForm.tenantEndDate.$setValidity('checkEndDate', false);
}
};
$scope.onAddEditTenantSubmitForm = onAddEditTenantSubmitForm;
$scope.tenantEdit = tenantEdit;
$scope.compareWithStartDate = compareWithStartDate;
$scope.state = state;
$scope.init = init;
}]);
})();```
My mistake here was not making the directive for the custom validation.

How to redirect to login page, if the process is not completed using angular2

I have a Popup, that is used for device verification.
So, once i click on login button after giving proper credentials, the popup opens if it is not trusted device, so i need to provide information then after successful validation, it redirects to home page.
My problem is, i clicked on login, so credentials needed for login is provided, and popup opens if its not trusted device, and if i refresh the page in middle of process, then it is redirecting to home page.
Can anyone help me how to solve this issue.
TS:
login(value: any) {
let userName = value.email.trim();
let passWord = value.password.trim();
let password = Md5.hashStr(passWord)
let params = { username: userName, password: password }
this.authService.doLogin(params)
.subscribe((data: any) => {
else if (data.Body.Data.token && data.Body.Data.id != -2) {
localStorage.setItem("userId_ls", data.Body.Data.userID)
localStorage.setItem('accountId_ls', data.Body.Data.accountID)
if (Cookie.get("DeviceUID") == null || this.DeviceUID == 'undefined') {
this.isUserDevice = true;
}
else if (this.DeviceUID != null && this.DeviceUID != undefined && this.userDId != null) {
let otpObj = { UserId: this.userDId, otp: "", Guid: this.DeviceUID, savedevice: "" }
this._userService.confirmDevice(otpObj).subscribe(resp => {
if(resp.message == "Invalid device.") {
Cookie.delete('DeviceUID');
this.router.navigate(['/login']);
window.location.reload();
} else {
this.router.navigate(['/home']); }
})
}
}
else {
console.log(data.message);
}
})
}
Routing.ts:
import { NgModule } from '#angular/core';
import { RouterModule, Routes } from '#angular/router';
import { CanActivatedAuthGuard } from './core/security-guard/auth.guard';
let routes: Routes = [
{ path: '', redirectTo: '/login', pathMatch: 'full' },
{ path: '', loadChildren: './home/home.module#HomeModule' },
{ path: 'login', loadChildren: './login/login.module#LoginModule' },
// { path: '**', loadChildren: './login/login.module#LoginModule' },
{ path: 'register', loadChildren: './register/register.module#RegisterModule' },
{ path: 'accountActivation/:userId/:activationCode', loadChildren: './activation/activation.module#ActivationModule' },
]
#NgModule({
imports: [
RouterModule.forRoot(routes, { useHash: true, enableTracing: false }
)
],
exports: [RouterModule]
})
export class AppRoutingModule { }
POPUP HTML:
<p-dialog header="New Device Verification" [(visible)]="isUserDevice" [responsive]="true" showEffect="fade" [modal]="true"
[width]="400">
<div class="form-group row g-mb-25">
<div class="col-sm-9 clear-fix">
<label class="col-sm-8 col-form-label g-color-gray-dark-v2 g-font-weight-700 g-mb-10">Choose OTP type
</label>
<div class="col-sm-9 clear-fix" *ngFor="let oType of otpTypes">
<label class="form-check-inline u-check g-pl-25">
<input type="radio" name="otpType" [value]="oType.otpType" (click)="chooseOtpType(oType)"> {{oType.otpType}}
</label>
</div>
<div>
<div *ngIf="isConfirmEmailOtp">
<input class="form-control col-lg-12" type="email" [(ngModel)]="enterEmail" name="myEmail" #myEmail="ngModel" email pattern="[a-zA-Z0-9.-_]{1,}#[a-zA-Z.-]{2,}[.]{1}[a-zA-Z]{2,}" (input)="submitButton &&submitButton.disabled = false"
#emailOTP>
<button (click)="generateEmailOtp(enterSms,enterEmail); submitButton.disabled = true;" class="btn pull-right otp" #submitButton [disabled] = "enterEmail === ''&& enterSms === ''" >Send OTP</button>
<div *ngIf="myEmail.errors && (myEmail.dirty || myEmail.touched)">
<br>
<div [hidden]="!myEmail.errors" class="error">
Invalid Email.
</div>
</div>
</div>
<div *ngIf="isSms">
<input class="form-control col-lg-12" type="number" [(ngModel)]="enterSms" #smsOTP (input)="submitButton && submitButton.disabled = false">
<button (click)="generateEmailOtp(enterSms,enterEmail); submitButton.disabled = true;" class="btn pull-right otp" #submitButton [disabled] = "enterEmail === ''&& enterSms === ''" >Send OTP</button>
</div>
</div>
</div>
<div class="col-lg-12 row g-mb-10" *ngIf="isConfirmOtp">
<label class="col-sm-4 col-form-label g-color-gray-dark-v2 g-font-weight-700 text-sm-left g-mb-10 nopadd">Verify OTP:
<span class="required">*</span>
</label>
<div class="col-sm-8">
<div class="input-group g-brd-primary--focus">
<input class="verifyPin" type="text" placeholder="Pin" [(ngModel)] = "otp">
</div>
</div>
</div>
</div>
<!-- End Login Verification -->
<p-footer>
<div class="col-sm-9 clear-fix saveDevice">
<label class="form-check-inline u-check g-pl-25">
<input class="g-hidden-xs-up g-pos-abs g-top-0 g-left-0" type="checkbox" [(ngModel)] = "checkboxSave">
<div class="u-check-icon-checkbox-v4 g-absolute-centered--y g-left-0">
<i class="fa" data-check-icon=""></i>
</div>
Save this device
</label>
</div>
<div class="ui-dialog-buttonpane ui-helper-clearfix popup">
<button type="button" pButton icon="fa-check" label="Save" class="btn u-btn-darkgray g-py-12 g-px-25 g-mr-10" (click)="cancelDevice()">Cancel</button>
<button type="button" pButton icon="fa-check" label="Save" class="btn u-btn-primary g-py-12 g-px-25" (click)="saveDeviceInfo(enterEmail, enterSms, otp,checkboxSave)" [disabled]="!otp">Ok</button>
</div>
</p-footer>
</p-dialog>
TS:
saveDeviceInfo(enterEmail, enterSms, otp, checkboxSave) {
var check = checkboxSave;
var uID = localStorage.getItem('userId_ls');
if (this.enterEmail != null && this.enterEmail != "") {
let otpObj = { userId: uID, otp: otp }
this._userService.confirmOtpEmail(otpObj).subscribe(resp => {
if (resp.Body.Data == "OTP verified successfully") {
let otpObj = { UserId: uID, otp: otp, Guid: "", savedevice: check, DeviceName: "webBrowser" }
if(!this.DeviceUID && this.otp || checkboxSave == true) {
this._userService.confirmDevice(otpObj).subscribe(resp => {
if (resp) {
Cookie.set('DeviceUID', resp.Guid);
this.router.navigate(['/home']);
}
})
}
}
else if (resp.Body.Data == "OTP is not valid.Please check the OTP") {
this.enterEmail = "";
this.enterSms = "";
this.otp = "";
this.msgs = [{ severity: 'error', summary: 'Error Message', detail: 'OTP is not valid.Please check the OTP' }];
this.isUserDevice = false;
this.isSms = false;
this.isConfirmEmailOtp = false;
this.isConfirmOtp = false;
Cookie.delete('token');
Cookie.delete('userType');
Cookie.delete('userID');
Cookie.delete('profilePic');
Cookie.delete('Id');
this.router.navigate(['/login']);
window.location.reload();
}
})
}
if (this.enterSms != null && this.enterSms != "") {
let otpObj = { userId: uID, otp: otp, isRequiredToken: this.isRequiredToken }
this._userService.confirmOtpSMS(otpObj).subscribe(resp => {
if (resp.Body.Data == "OTP verified successfully") {
let otpObj = { UserId: uID, otp: otp, Guid: "", savedevice: check, DeviceName: "webBrowser" }
if(!this.DeviceUID && this.otp || checkboxSave == true) {
this._userService.confirmDevice(otpObj).subscribe(resp => {
if (resp) {
Cookie.set('DeviceUID', resp.Guid);
this.router.navigate(['/home']);
}
})
}
} else if (resp.Header.Message == "User Does Not Exist For This OTP") {
this.enterEmail = "";
this.enterSms = "";
this.otp = "";
this.msgs = [{ severity: 'error', summary: 'Error Message', detail: 'User Does Not Exist For This OTP' }];
this.isUserDevice = false;
this.isSms = false;
this.isConfirmEmailOtp = false;
this.isConfirmOtp = false;
Cookie.delete('token');
Cookie.delete('userType');
Cookie.delete('userID');
Cookie.delete('profilePic');
Cookie.delete('Id');
this.router.navigate(['/login']);
window.location.reload();
}
})
}
}
Here that popup function is coming after success of login, Please help.
First of all, when your popup window(I assuming it's a 'dialog' such as Angular Material dialog) comes out, the URL won't change.
So, according to your description, your situation seems to be like:
-Just before you refresh, the url has already changed, or say you already successfully logged in. That's why it will navigate to the home page.
-The problem is you should have a routing guard everytime you enter a page to check if the user is logged in. Also, you will need authentification in your back-end.
The official routing documents of Angular explained almost everything pretty clearly and will be very useful. Here is the link: https://angular.io/guide/router
Hopes this helps you.
From this line ,
It must go to home page, after my popup is clicked on Ok button or if DeviceId is already present in cookies then it must go.
Handle popup ok click event (or) do like this using cookie
else{
let deviceId= Cookie.get('DeviceId ');
if(deviceId && deviceId!=null && deviceId!=undefined){
this.router.navigate(['/home']); }
}
}
show your _userService.confirmDevice which confirmation package you are used?

Getting error in input-group-addon when validating the field using ajax and jquery in codeigniter

Now its been 46 day's till i am stuck with this. Or there is Another way to Do this.
I Know This very simple But How can i wrap input-group under form-group. I am submitting the form data in codeigniter using ajax and showing validation errors.
The issue is that input-group-addon wraps to the next line underneath the form field when the error control is added by Jquery Validate.
Controller
function infoValidation() {
$result = array('status' => false, 'message' => array());
$this->form_validation->set_error_delimiters('<div class="text-danger">','</div>');
if ($this->form_validation->run('company_registration')) {
$result['status'] = true;
}else {
foreach ($_POST as $key => $value) {
$result['message'][$key] = form_error($key);
}
}
echo json_encode($result);
}
view
<div class="col-lg-6">
<div class="form-group">
<div class="input-group">
<span class="input-group-addon">*</span>
<input type = "text" name="creditCardNumber" class="form-control input-md" id="creditCardNumber" placeholder="Mobile No">
</div>
</div>
ajax
I have also try to append the element But Nothing Happens
$.ajax({
url : me.attr('action'),
dataType : 'json',
type : 'POST',
data : me.serialize(),
success: function(resp) {
console.log(resp);
if (resp.status == true) {
$('#myModal').modal('show');
$(".form-group").removeClass('has-error').removeClass('has-success');
$(".text-danger").remove();
}else {
$('#msg').html('<div class="well"><h5>Please Check Your Details</h5></div>');
$.each(resp.message, function(key, value) {
var element = $("#"+key);
element.closest('div.form-group, div.input-group')
.addClass(value.length > 0 ? 'has-error' : 'has-success')
.find('.text-danger').remove();
element.after(value);
});
}
}
});
I think you need to override the jQuery validate plugin method in order to get compatibility with bootstrap.
Refer http://jsfiddle.net/mapb_1990/hTPY7/7/
Example code
$('form').validate({
rules: {
firstname: {
minlength: 3,
maxlength: 15,
required: true
},
lastname: {
minlength: 3,
maxlength: 15,
required: true
}
},
highlight: function(element) {
$(element).closest('.form-group').addClass('has-error');
},
unhighlight: function(element) {
$(element).closest('.form-group').removeClass('has-error');
},
errorElement: 'span',
errorClass: 'help-block',
errorPlacement: function(error, element) {
if(element.parent('.input-group').length) {
error.insertAfter(element.parent());
} else {
error.insertAfter(element);
}
}
});
Just add label for error at your desired location:
<label for="creditCardNumber" generated="true" class="error">
<div class="col-lg-6">
<div class="form-group">
<div class="input-group">
<span class="input-group-addon">*</span>
<input type = "text" name="creditCardNumber" class="form-control input-md" id="creditCardNumber" placeholder="Mobile No">
</div>
<label for="creditCardNumber" generated="true" class="error"></label>
</div>

Categories