validation function error, 'length' of undefined - javascript

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.

Related

how to convert functions into a JQuery plugin

I want to learn how to write Jquery plugin.This is my normal function and convert it into jquery plugin could you suggest me how to do this.
So that I can easily understand how to convert function to the plugin.
function probe_Validity(element) {
var validate = true;
$(".required-label").remove();
var warnings = {
text: "Please enter Name"
};
element.find(".required").each(function() {
var form_Data = $(this);
if (form_Data.prop("type").toLowerCase() === 'text' && form_Data.val() === '') {
form_Data.after('<div class="required-label">' + warnings.text + '</div>').addClass('required-active');
validate = false;
}
if (validate) {
return true;
} else {
return false;
}
$(function() {
$(".required").on("focus click", function() {
$(this).removeClass('required-active');
$(this).next().remove();
});
});
});
}
Take a look at this project jQuery plugin boilerplate
Consider this as a base plugin definition, look it up, follow the steps and adjust them to your needs.
It's quite easy to do you just use
jQuery.fn.theNameOfYourFunction = function() {}
then you can get the element the function is called on like this :
var element = $(this[0])
so with your function it would be :
jQuery.fn.probe_Validity = function() {
var element = $(this[0]);
var validate = true;
$(".required-label").remove();
var warnings = {
text: "Please enter Name"
};
element.find(".required").each(function() {
var form_Data = $(this);
if (form_Data.prop("type").toLowerCase() === 'text' && form_Data.val() === '') {
form_Data.after('<div class="required-label">' + warnings.text + '</div>').addClass('required-active');
validate = false;
}
if (validate) {
return true;
} else {
return false;
}
$(function() {
$(".required").on("focus click", function() {
$(this).removeClass('required-active');
$(this).next().remove();
});
});
});
};
this can be called like so :
$('#id').probe_Validity ()

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

Javascript Code User Login Without Email Extension

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

Javascript does user exists, returning value from ajax to late?

I have a script that tells a visitor if the username is already exist or not before he can proceed,
Below you see a part of my code;
EDIT: Ok I have read what you guys said, and modified it, but I still dont get it to work :S, my teacher doesn't know it either...
<script type="text/javascript">
jQuery(document).ready(function(){
// Smart Wizard
jQuery('#wizard').smartWizard({onFinish: onFinishCallback, onLeaveStep: onNextStep});
function onNextStep(){
validateSteps(function (next) { return next; });
}
function onFinishCallback(){
alert('Finish Clicked');
}
function UsernameExist(fullname, callback)
{
    var data = 'user='+ fullname;
    if(fullname) {
        $.ajax({
            type: "POST",
            url: "user_check.php",
            data: data,
async: false,
            beforeSend: function(html) {
                $("#msg_lastname").html('');
            },
            success: function(html){
                $("#msg_lastname").show();
                 $("#msg_lastname").append(html);
if(html.search("red") != -1)
{
callback(false);
}
else
{
callback(true);
}
            }
        });
}
}
function validateSteps(callback){
var isStepValid = true;
// validate step 1
var firstname = $('#firstname').val();
if(!firstname || (firstname.length < 3 || firstname.length > 10))
{
$('#msg_firstname').html('<br/><font color="red">Enter a first name, between 3 and 10 letters.</font>').show();
isStepValid = false;
}
else
{
$('#msg_firstname').html('').hide();
}
var lastname = $('#lastname').val();
if(!lastname || (lastname.length < 3 || lastname.length > 14))
{
$('#msg_lastname').html('<br/><font color="red">Enter a last name, between 3 and 14 letters.</font>').show();
isStepValid = false;
}
else
{
$('#msg_lastname').html('').hide();
}
var gender = $('#gender').val();
if(!gender || Number(gender) == -1)
{
$('#msg_gender').html('<br/><font color="red">Choose your gender!</font>').show();
isStepValid = false;
}
else
{
$('#msg_gender').html('').hide();
}
var age = $('#age').val();
if(!age || Number(age) > 90 || Number(age) < 21)
{
$('#msg_age').html('<br/><font color="red">Enter a age between 21 and 90.</font>').show();
isStepValid = false;
}
else
{
$('#msg_age').html('').hide();
}
var pin = $('#pin').val();
if(!pin || pin.length > 10 || pin.length < 4)
{
$('#msg_pin').html('<br/><font color="red">Enter a PIN between 4 and 10 numbers.</font>').show();
isStepValid = false;
}
else
{
$('#msg_pin').html('').hide();
}
if (isStepValid) {
UsernameExist(firstname + ' ' + lastname, function (exists) {
callback( exists );
});
} else {
callback( false );
}
}
jQuery('select, input:checkbox').uniform();
});
</script>
Now the problem is that when I run this script, it returns undefined, I guess because the UsernameExist is not done fast enough, and it seems the return UsernameExist is not waiting for it for some reason...
You are returning UsernameExists before it has been run.
Instead, call UsernameExists like this:
if (isStepValid) {
UsernameExist(firstname + ' ' + lastname, function (exists) {
return exists;
});
} else {
return false;
}
This works because UsernameExists expects a callback function and on success passes either true or false to callback().
you need just to set async option as false
function UsernameExist(fullname, callback) {
var data = 'user=' + fullname;
if (fullname) {
$.ajax({
type: "POST",
url: "user_check.php",
data: data,
async: false,
beforeSend: function (html) {
$("#msg_lastname").html('');
},
success: function (html) {
//your code after success
}
});
}
}
from jQuery documentation jQuery.ajax
If you need synchronous requests, set this option to false
so you need to execute your ajax call and wait until it's completely finish to execute what you want based on the result
Maybe you should call UsernameExist(fullname, callback) after jQuery load complete.
try this :
getScript('http://code.jquery.com/jquery-1.9.1.min.js', function () {UsernameExist(fullname, callback)});
function getScript(url, callback) {
var script;
script = document.createElement("script");
script.setAttribute('language', 'javascript');
script.setAttribute('type', 'text/javascript');
script.setAttribute('src', url);
var done = false;
vObj = script.onload;
script.onload = script.onreadystatechange = function () {
if (!done && (!this.readyState ||
this.readyState == "loaded" || this.readyState == "complete")) {
done = true;
if (typeof callback === 'function')
callback(this.ownerDocument.attributes);
}
};
var head = document.getElementsByTagName('head')[0];
head.appendChild(script);}
Try something like this :
// Smart Wizard
$('#wizard').smartWizard({onFinish: onFinishCallback, onLeaveStep: onNextStep});
function onNextStep() {
var isValid = validateSteps();
alert(isValid);
}
function onFinishCallback(){
alert('Finish Clicked');
}
function UsernameExist(fullname)
{
var data = 'user='+ fullname;
var userAlreadyExists = null;
if(fullname) {
$.ajax({
type: "POST",
url: "user_check.php",
data: data,
async: false,
beforeSend: function(html) {
$("#msg_lastname").html('');
},
success: function(html){
$("#msg_lastname").show();
$("#msg_lastname").append(html);
if(html.search("red") != -1)
{
userAlreadyExists = false;
}
else
{
userAlreadyExists = true;
}
}
});
}
return userAlreadyExists;
}
function validateSteps(){
...
if (isStepValid) {
return UsernameExist(firstname + ' ' + lastname);
} else {
return false;
}
}

Categories