Javascript Code User Login Without Email Extension - javascript

I'm having a problem and don't know how the form will accept the username without email extension for example i can enter "pro" only in "pro#domain.com"
Here's my code:
function loginHI(menu){
$(".hopplerTextboxLogin").focusin(function(){
hopplerTextboxFocused($(this));
}).focusout(function(){
$(this).removeClass("hopplerTextboxBorderBlue").addClass("hopplerTextbox");
});
$("#loginForm input").keyup(function(e){
if(e.keyCode == 13){
$("#btnLogin").click();
}
});
$("#btnLogin, #btnLogin2").click(function(){
//variable for email
var get_email = $("#j_username").val();
var get_pass = $("#j_password").val();
//validation
if(get_email=="" && get_pass==""){
somethingIsWrongHere("divUsername_login","Required fields");
somethingIsWrongHere("divPassword_login","Required fields");
return false;
}
if(get_email=="" || !isValidEmailAddress(get_email)){
somethingIsWrongHere("divUsername_login","Invalid email address");
return false;
}
if(get_pass == ""){
somethingIsWrongHere("divPassword_login","Password is required");
return false;
}
var result_page = setProjectName + "/j_spring_security_check";
$("#loginForm_message").html("<div class=\"loading_message_login\">logging in...</div>").fadeIn();
$("#cboxContent").removeClass("cboxContentHeight").addClass("cboxContentHeightMessage");
$.ajax({
type: 'POST',
url: result_page,
data: $("#loginForm").serialize(),
beforeSend: function (xhr) {
xhr.setRequestHeader("X-Ajax-call", "true");
},
success: function(data) {
if(data.result==1){
localStorage.shortlists = "";
var sl_array = [];
localStorage.userFullName = data.firstName+" "+data.lastName;
var user_url = "HICollection3/select?q=id%3A"+data.userId+"&wt=json&indent=true";
var sl_url = "ShortList_Collection/select?q=removed%3Afalse+AND+user_id%3A"+data.userId+"&rows=1000&wt=json&indent=true&json.wrf=?";
$.get("properties/querySolr",{url : sl_url},function(result) {
solr_results = result;
var obj = $.parseJSON(solr_results);
console.log("obj.numFound" + obj.numFound);
var sl = obj.docs;
$.each(sl,function(index){
sl_array.push(sl[index].property_id);
});
localStorage.shortlists = sl_array;
/*EMBEDDED HIDDENLIST FXN*/
var hl_array = [];
var hl_url = "HiddenList_Collection/select?q=user_id%3A"+data.userId+"&rows=1000&wt=json&indent=true&json.wrf=?";
$.get("properties/querySolr",{url : hl_url},function(result2) {
solr_results2 = result2;
var obj2 = $.parseJSON(solr_results2);
console.log("obj2.numFound" + obj2.numFound);
var hl = obj2.docs;
$.each(hl,function(index){
hl_array.push(hl[index].property_id);
});
localStorage.hiddenlists = hl_array;
$.get("properties/querySolr",{url : user_url},function(result3) {
var solr_results3 = result3;
var obj3 = $.parseJSON(solr_results3);
console.log("obj3.numFound" + obj3.numFound);
var user_res = obj3.docs;
localStorage.userContact="";
localStorage.userFullName="";
localStorage.userEmail="";
$.each(user_res,function(index){
localStorage.userFullName = user_res[index].firstName+" "+user_res[index].lastName;
localStorage.userEmail = user_res[index].email;
if(user_res[index].mobile!=undefined || user_res[index].mobile!="")
localStorage.userContact = user_res[index].mobile;
else if(user_res[index].telephone!=undefined || user_res[index].telephone!="")
localStorage.userContact = user_res[index].telephone;
else
localStorage.userContact = "";
});
setTimeout(function(){
location.reload();
},1000);
});
});
});
}
else{
somethingIsWrongHere("",data.result);
}
}
});
return false;
});
$("#keepMeLoggedIn").click(function(){
$("#rememberMe").trigger("click");
});
}
the user log-in should accept also the the whole email address.
This is the code for isValidEmailAddress function
function isValidEmailAddress(emailAddress) {
var pattern = new RegExp(/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))#((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i);
return pattern.test(emailAddress);
};

Once again... the function test you will use will depend on what characters you would like to allow. If you want to only allow letters and numbers you could use...
function isValidUsername(username) {
var pattern = new RegExp(/^[a-zA-Z0-9]+$/);
return pattern.test(username);
}
and if you wanted to allow periods and # symbols so that you could have emails used as the username as optional...
function isValidUserName(username) {
var pattern = new RegExp(/^[a-zA-Z0-9\.\#]+$/);
return pattern.test(username);
}
Note that the user could use any combination of letters numbers and # symbols and periods if you use the second function. So, they could enter ###... or ddd#example.com or adfsadf8347

Related

How to execute a JS function if the parameters do not match?

I took this code from internet to modify, to practice JS, though I fail to call the function when the input length is equal 0. So basically I click on the "Add a column" and it opens the console to give the name of the column you want to make, though when the input length as I said is equal to 0, it raises and alert, but it doesn't ask again for the input (I don't know how to call the function so the input console will show up again).
Down below you have the JS code, for the whole code (html, css, js) click here.
function Column(name) {
if (name.length > 0) {
var self = this; // useful for nested functions
this.id = randomString();
this.name = name;
this.$element = createColumn();
function createColumn() {
var $column = $("<div>").addClass("column");
var $columnTitle = $("<h2>")
.addClass("column-title")
.text(self.name);
var $columnCardList = $("<ul>").addClass("column-card-list");
var $columnDelete = $("<button>")
.addClass("btn-delete")
.text("x");
var $columnAddCard = $("<button>")
.addClass("add-card")
.text("Add a card");
$columnDelete.click(function() {
self.removeColumn();
});
$columnAddCard.click(function(event) {
self.addCard(new Card(prompt("Enter the name of the card")));
});
$column
.append($columnTitle)
.append($columnDelete)
.append($columnAddCard)
.append($columnCardList);
return $column;
}
} else if (name.length == 0) {
alert("please type something");
} else {
return;
}
}
Column.prototype = {
addCard: function(card) {
this.$element.children("ul").append(card.$element);
},
removeColumn: function() {
this.$element.remove();
}
};
function Card(description) {
var self = this;
this.id = randomString();
this.description = description;
this.$element = createCard();
function createCard() {
var $card = $("<li>").addClass("card");
var $cardDescription = $("<p>")
.addClass("card-description")
.text(self.description);
var $cardDelete = $("<button>")
.addClass("btn-delete")
.text("x");
$cardDelete.click(function() {
self.removeCard();
});
$card.append($cardDelete).append($cardDescription);
return $card;
}
}
Card.prototype = {
removeCard: function() {
this.$element.remove();
}
};
var board = {
name: "Kanban Board",
addColumn: function(column) {
this.$element.append(column.$element);
initSortable();
},
$element: $("#board .column-container")
};
function initSortable() {
$(".column-card-list")
.sortable({
connectWith: ".column-card-list",
placeholder: "card-placeholder"
})
.disableSelection();
}
$(".create-column").click(function() {
var name = prompt("Enter a column name");
var column = new Column(name);
board.addColumn(column);
});
// ADDING CARDS TO COLUMNS
todoColumn.addCard(card1);
doingColumn.addCard(card2);
});
After the line:
alert("please type something");
Add the following:
$(".create-column").click();
That programmatically "clicks" the Create Column button.
If you want to prompt the user to enter column name if length is 0, just add this lines of code to your if-stament:
var name = prompt("Enter a column name");
var column = new Column(name);
board.addColumn(column);.
As shown below:
else if (name.length == 0) {
alert("please type something");
var name = prompt("Enter a column name");
var column = new Column(name);
board.addColumn(column);
} else {
return;
}
If that was your question, this should be able to fix it.

How do I get a return value from a Handler function in JavaScript?

I am able to get the information from the object I am using to store the form information, when the one tries to fire the submit without filling in the fields successfully, but when I enter all the information correctly I can't seem to obtain the same upon success?
var theForm = document.getElementsByTagName('form')[0];
var firstNameInput = document.getElementById('firstNameInput');
var lastNameInput = document.getElementById('lastNameInput');
var emailInput = document.getElementById('emailInput');
var stateInput = document.getElementById('stateInput');
var theButton = document.querySelector('input[type=submit]');
// Wire the form's submit event to a callback
theForm.addEventListener('submit', validate);
function validate(e) {
// Error tracking variable
var error = false;
// Do validations
var emailPattern = /^(([^<>()\[\]\\.,;:\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,}))$/;
var formData = {
'firstName': null,
'lastName': null,
'email': null,
'stateInput': null
}
if ((firstNameInput.value == '') || (firstNameInput.value == null)) {
firstNameInput.classList.add('invalid-input');
firstNameInput.nextElementSibling.style.display = 'block';
firstNameInput.nextElementSibling.innerHTML = 'Not valid!';
error = true;
}
if ((lastNameInput.value == '') || (lastNameInput.value == null)) {
lastNameInput.classList.add('invalid-input');
lastNameInput.nextElementSibling.style.display = 'block';
lastNameInput.nextElementSibling.innerHTML = 'Not valid!';
error = true;
}
if (!emailPattern.test(emailInput.value)) {
emailInput.classList.add('invalid-input');
emailInput.nextElementSibling.style.display = 'block';
emailInput.nextElementSibling.innerHTML = 'Please enter valid email address!';
error = true;
}
if ((stateInput.value == 'selectstate')) {
stateInput.classList.add('invalid-input');
stateInput.nextElementSibling.style.display = 'block';
stateInput.nextElementSibling.innerHTML = 'Not valid!';
error = true;
}
// If error, stop the event
if (error) {
e.preventDefault();
e.stopPropagation();
console.log('There is no data from the form: ');
for (var prop in formData) {
console.log(prop + ' : ' + formData[prop]);
}
return false;
} else {
formData['firstName'] = firstNameInput.value;
formData['lastName'] = lastNameInput.value;
formData['email'] = emailInput.value;
formData['stateInput'] = stateInput.value;
console.log('There is now data from the form: :) ');
for (var prop in formData) {
console.log(prop + ' : ' + formData[prop]);
}
return true;
}
}
I tried this:
var result = theForm.addEventListener('submit', validate);
if (result) {
console.log(result);
}
Any help would be appreciated!
According to w3schools.com, this function, addEventListener() does not return anything.
https://www.w3schools.com/jsref/met_element_addeventlistener.asp
If you'd like to know if the event listener is installed properly, you need to check if the function exists:
if(theForm.addEventListener){
theForm.addEventListener('submit', validate);
}else{
theForm.attachEvent('onclick', validate);
}

How to access data from ajax call after the ajax call ends

I am making a ajax calls that returns me some data from the server. I work on string function on the data that come from ajax call. From my knowledge i can see the string operation begins before the ajax call gets over. Often giving me undefined error. Here is my ajax call
$.ajax({
type: "POST",
url: "/add_director",
headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
data: formData,
cache: false,
contentType: false,
processData: false,
success: function(data) {
$('#addDirModal').modal('hide');
insertDirector(data);
},
error : function(xhr ,status ,error)
{
console.log(xhr);
alert(xhr);
}
});
Here is my insertDirector function
function insertDirector(data){
console.log(data);
if (data.msg == "1") {
$.each(data,function(key,value){
var dir_name = value.dir_name;
var dir_pan = value.dir_pan;
var dir_din = value.dir_din;
var dir_addr = value.dir_addr;
var dir_id = value.id;
var dir_img = value.dir_img;
if (dir_name.val().length > 15) {
var dir_r_name = dir_name.substr(0,15);
}
else{
var dir_r_name = dir_name;
}
});
}
}
Here when i work on substr() it throws the error Cannot read property 'val' of undefined. I can see this is because the substr() is executed before the ajax request is completed. how do i fix this ?
EDITED
Here is the response
{"msg":"1","director":{"dir_name":"Naveen","dir_pan":"AAAAA1111B","dir_din":"123456","dir_addr":"dsadasdasdasdsadasdas","dir_img":"1490852438.jpg","user_id":3,"updated_at":"2017-03-30 05:40:38","created_at":"2017-03-30 05:40:38","id":15}}
Its not clear why you use the $.each here (you can omit it and use data.director instead of value), but if it is possible that your data contain several 'director' objects and you want to iterate through all of them, then you should change the insertDirector code to skip the 'msg' key as it doesn't have dir_name, dir_plan, ... properties:
function insertDirector(data) {
console.log(data);
if (data.msg == "1") {
$.each(data, function (key, value) {
if (key == "director") { //or if (key != "msg")
var dir_name = value.dir_name;
var dir_pan = value.dir_pan;
var dir_din = value.dir_din;
var dir_addr = value.dir_addr;
var dir_id = value.id;
var dir_img = value.dir_img;
var dir_r_name = (dir_name.length > 15 ? dir_name.substr(0, 15) : dir_name);
//if (dir_name.length > 15) {
// var dir_r_name = dir_name.substr(0, 15);
//}
//else {
// var dir_r_name = dir_name;
//}
}
});
}
}
also, note that dir_name.val().length is wrong as dir_name is a string (.val() is not required)
change
if (dir_name.val().length > 15) {
var dir_r_name = dir_name.substr(0,15);
}
to
if (dir_name.length > 15) {
var dir_r_name = dir_name.substr(0,15);
}
try this way :
function insertDirector(data) {
console.log(data);
if (data.msg == "1") {
var dir_name = data.director.dir_name;
var dir_pan = data.director.dir_pan;
var dir_din = data.director.dir_din;
var dir_addr = data.director.dir_addr;
var dir_id = data.director.id;
var dir_img = data.director.dir_img;
if (dir_name.length > 15) {
var dir_r_name = dir_name.substr(0, 15);
}
else {
var dir_r_name = dir_name;
}
}
}
After seeing the data you posted, it is easy to find issue.
Here, the issue is:
Your function:
function insertDirector(data){
console.log(data);
if (data.msg == "1") {
$.each(data,function(key,value){
var dir_name = value.dir_name;
var dir_pan = value.dir_pan;
var dir_din = value.dir_din;
var dir_addr = value.dir_addr;
var dir_id = value.id;
var dir_img = value.dir_img;
if (dir_name.val().length > 15) {
var dir_r_name = dir_name.substr(0,15);
}
else{
var dir_r_name = dir_name;
}
});
}
}
Here, when you do $.each, every object inside data will be traversed. Now, your first value inside data is msg:1. This is not a object. As a result, on first iteration, key is 'msg' but value is '1'. Now this value can't have dir_name so undefined is returned. As a result dir_name.val() generates error.
Try it like this:
function insertDirector(data){
console.log(data);
if (data.msg == "1") {
$.each(data,function(key,value){
if(key==="director"){
var dir_name = value.dir_name;
var dir_pan = value.dir_pan;
var dir_din = value.dir_din;
var dir_addr = value.dir_addr;
var dir_id = value.id;
var dir_img = value.dir_img;
if (dir_name.val().length > 15) {
var dir_r_name = dir_name.substr(0,15);
}
else{
var dir_r_name = dir_name;
}
}
});
}
}

validation function error, 'length' of undefined

I am making a validation function, submitForm function is to check other function return value true or false, but I have this error, I don't know why.
Uncaught TypeError: Cannot read property 'length' of undefined
var ClassSignUpValidation = function (){};
ClassSignUpValidation.prototype.CheckName = function (_target)
{
return false;
}
ClassSignUpValidation.prototype.CheckPassword = function (_target)
{
return false;
}
//SUBMIT FORM VALIDATION
ClassSignUpValidation.prototype.SubmitForm = function (event)
{
var sumbit_errorspan = $("#submit-errorResult");
//array validation function
var validators = [this.CheckName, this.CheckPassword];
// bypass all function
var valid = validators.reduce(function(valid, validator){
return validator() && valid;
}, true);
if(valid){
sumbit_errorspan.html('');
}else{
sumbit_errorspan.css('color', 'red');
sumbit_errorspan.html('sumbit not requirements.');
}
return valid;
}
error point
ClassSignUpValidation.prototype.CheckName = function (_target)
{
//set target id to jquery
_target = "#" + _target;
//set variable
var username_target = $(_target);
var username_value = username_target.val();
var username_errorspan = $("#user-errorResult");
****//here is the error****
if (username_value.length >= 4){
$.ajax({
type:"POST",
url:"/main/class/classvalidation.php",
async:false,
data:{
"username": username_value
},
success: function(data)
{
var usernameAvailable = JSON.parse(data);
var color = usernameAvailable.exists ? "#dfe0e6" : "red";
username_errorspan.html(usernameAvailable.message);
username_errorspan.css("color", color);
username_target.css("border-color", color);
if(usernameAvailable.exists === true){
return true;
}
}
});
};
return false;
}
error here is the error point in
if (username_value.length >= 4){
Your IF statement should look like this:
username_value && username_value.length >= 4
That way you'll be sure that there is a value (and so an element as well) and that it's length is greater than 4.

'$' and 'document' are not defined - JQuery Mobile

JSHint Problems. console and FBT are also not defined.
As a result my button in page-signup does not work.
................................................................................................................................................................
(function () {
var emailAddressIsValid = 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);
};
var passwordsMatch = function (password, passwordConfirm) {
return password === passwordConfirm;
};
var passwordIsComplex = function (password) {
// TODO: implement password complexity rules here. There should be similar rule on the server side.
return true;
};
$(document).delegate("#page-signup", "pagebeforecreate", function () {
var $signUpPage = $("#page-signup"),
$btnSubmit = $("#btn-submit", $signUpPage);
$btnSubmit.off("tap").on("tap", function () {
var $ctnErr = $("#ctn-err", $signUpPage),
$txtFirstName = $("#txt-first-name", $signUpPage),
$txtLastName = $("#txt-last-name", $signUpPage),
$txtEmailAddress = $("#txt-email-address", $signUpPage),
$txtPassword = $("#txt-password", $signUpPage),
$txtPasswordConfirm = $("#txt-password-confirm", $signUpPage);
var firstName = $txtFirstName.val().trim(),
lastName = $txtLastName.val().trim(),
emailAddress = $txtEmailAddress.val().trim(),
password = $txtPassword.val().trim(),
passwordConfirm = $txtPasswordConfirm.val().trim(),
invalidInput = false,
invisibleStyle = "bi-invisible",
invalidInputStyle = "bi-invalid-input";
// Reset styles.
$ctnErr.removeClass().addClass(invisibleStyle);
$txtFirstName.removeClass(invalidInputStyle);
$txtLastName.removeClass(invalidInputStyle);
$txtEmailAddress.removeClass(invalidInputStyle);
$txtPassword.removeClass(invalidInputStyle);
$txtPasswordConfirm.removeClass(invalidInputStyle);
// Flag each invalid field.
if (firstName.length === 0) {
$txtFirstName.addClass(invalidInputStyle);
invalidInput = true;
}
if (lastName.length === 0) {
$txtLastName.addClass(invalidInputStyle);
invalidInput = true;
}
if (emailAddress.length === 0) {
$txtEmailAddress.addClass(invalidInputStyle);
invalidInput = true;
}
if (password.length === 0) {
$txtPassword.addClass(invalidInputStyle);
invalidInput = true;
}
if (passwordConfirm.length === 0) {
$txtPasswordConfirm.addClass(invalidInputStyle);
invalidInput = true;
}
// Make sure that all the required fields have values.
if (invalidInput) {
$ctnErr.html("<p>Please enter all the required fields.</p>");
$ctnErr.addClass("bi-ctn-err").slideDown();
return;
}
if (!emailAddressIsValid(emailAddress)) {
$ctnErr.html("<p>Please enter a valid email address.</p>");
$ctnErr.addClass("bi-ctn-err").slideDown();
$txtEmailAddress.addClass(invalidInputStyle);
return;
}
if (!passwordsMatch(password, passwordConfirm)) {
$ctnErr.html("<p>Your passwords don't match.</p>");
$ctnErr.addClass("bi-ctn-err").slideDown();
$txtPassword.addClass(invalidInputStyle);
$txtPasswordConfirm.addClass(invalidInputStyle);
return;
}
if (!passwordIsComplex(password)) {
// TODO: Use error message to explain password rules.
$ctnErr.html("<p>Your password is very easy to guess. Please try a more complex password.</p>");
$ctnErr.addClass("bi-ctn-err").slideDown();
$txtPassword.addClass(invalidInputStyle);
$txtPasswordConfirm.addClass(invalidInputStyle);
return;
}
$.ajax({
type: 'POST',
url: FBT.Settings.signUpUrl,
data:"email=" + emailAddress + "&firstName=" + firstName + "&lastName=" + lastName + "&password=" + password + "&passwordConfirm=" + passwordConfirm,
success: function (resp) {
console.log("success");
if (resp.success === true) {
$.mobile.navigate("signup-succeeded.html");
return;
}
if (resp.extras.msg) {
switch (resp.extras.msg) {
case FBT.ApiMessages.DB_ERROR:
case FBT.ApiMessages.COULD_NOT_CREATE_USER:
// TODO: Use a friendlier error message below.
$ctnErr.html("<p>Oops! A problem occured while trying to register you. Please try again in a few minutes.</p>");
$ctnErr.addClass("bi-ctn-err").slideDown();
break;
case FBT.ApiMessages.EMAIL_ALREADY_EXISTS:
$ctnErr.html("<p>The email address that you provided is already registered.</p>");
$ctnErr.addClass("bi-ctn-err").slideDown();
$txtEmailAddress.addClass(invalidInputStyle);
break;
}
}
},
error: function (e) {
console.log(e.message);
// TODO: Use a friendlier error message below.
$ctnErr.html("<p>Oops! A problem occured while trying to register you. Please try again in a few minutes.</p>");
$ctnErr.addClass("bi-ctn-err").slideDown();
}
});
});
});
})();

Categories