I'm getting an array of Strings, and if the array has items I want to do one thing and if not I want to do the other. I'm not sure how to check if the array is empty of not. Also when stepping through my code in chrome debugger even if the array has items in it the length is still 0 so I can't use formErrors.length > 0.
Here's my code for getting the errors. This works fine and returns an array of error strings or an empty array:
var formErrors = validateFormData(formData);
function validateFormData(data) {
var errors = [];
if (data["title"].length == 0) {
errors["title"] = "Project title required";
}
if (data["client"].length == 0) {
errors["client"] = "Client name required";
}
if (data["date"].length == 0) {
errors["date"] = "Date required";
} else if (!isValidDateFormat(data["date"])) {
errors["date"] = "Date format invalid - Format: dd/mm/yyyy";
}
if (data["status"] == "") {
errors["status"] = "Please select current status for this project";
}
if (data["type"] == "") {
errors["type"] = "Please select a project type";
}
if (data["extras"].length == 0) {
errors["extras"] = "You must select at least one extra for this project";
}
return errors;
}
Then I want to do one thing if there's no errors and another if there is. But this is the bit that won't work for me.
if (formErrors !== {}) {
displayFormErrors(formErrors);
event.preventDefault();
}
else {
clearForm();
}
I've tried multiple ways and nothing has worked so far. Any help is appreciated, thank you!
EDIT
I can't use the .length on the array cause the length is 0 even when it has data.
Screenshot of chrome debugger
I'm slightly confused about what people are asking sorry, i'm not an expert here is my full code to get a better understanding of what i'm trying to do.
$(document).ready(function () {
$('#submit').on("click", onSubmitForm);
function onSubmitForm(event) {
clearErrorMessages();
var formData = getFormData();
var formErrors = validateFormData(formData);
if (formErrors) {
displayFormErrors(formErrors);
event.preventDefault();
}
else {
clearForm();
// Do other stuff
}
}
function clearForm() {
$('#title').val("");
$('#client').val("");
$('#date').val("");
$('#status').val("planning");
$('#description').val("");
$('.type').prop('checked', false);
$('.extra').prop('checked', false);
$('#title').focus();
}
function clearErrorMessages() {
$(".uk-text-danger").html("");
}
function getFormData () {
var data = [];
data["title"] = $('#title').val();
data["client"] = $('#client').val();
data["date"] = $('#date').val();
data["status"] = $('select#status option:selected').val();
data["description"] = $('#description').val();
if ($("input[name='type']:checked").length > 0) {
data["type"] = $("input[name='type']:checked").val();
}
else {
data["type"] = "";
}
data["extras"] = [];
$.each($("input[name='extras[]']:checked"), function(index, radio) {
data["extras"].push(radio.value);
});
return data;
}
function validateFormData(data) {
var errors = [];
if (data["title"].length == 0) {
errors["title"] = "Project title required";
}
if (data["client"].length == 0) {
errors["client"] = "Client name required";
}
if (data["date"].length == 0) {
errors["date"] = "Date required";
} else if (!isValidDateFormat(data["date"])) {
errors["date"] = "Date format invalid - Format: dd/mm/yyyy";
}
if (data["status"] == "") {
errors["status"] = "Please select current status for this project";
}
if (data["type"] == "") {
errors["type"] = "Please select a project type";
}
if (data["extras"].length == 0) {
errors["extras"] = "You must select at least one extra for this project";
}
return errors;
}
function displayFormErrors(errors) {
for (var field in errors) {
var errorElementId = field + "Error";
$('#' + errorElementId).html(errors[field]);
}
} });
Sorry if this is too much i'm not sure what else to do.
An empty array, string or object is "falsy" in JavaScript.
That is, you can pass the array, string or object directly into the if conditional and it will run depending on if something is in there or not.
if ([]) {
// this will never run
}
if ('') {
// this won't run either
}
if ({}) {
// nor will this
}
var errors = {}; inside the validateFormData function.
And then compare the the object like this.
if (JSON.stringify( formErrors ) !== '{}') { //do something}else { //do something}
Where are you verifying if the formErrors is empty? This verification (the if-else) should be inside the function which submits the form.
Also try using:
if (formErrors.length > 0)
instead of:
if (formErrors !== {})
Related
I have a function that check Username in a form,parent function i check if there are empty field, and now i wanna pass usernameValidat() in inside onSubmit() to check if it match with my username validation. Can anyone give me the answer to solve this issue please
onSubmit() {
var text = "Please insert ";
for (let i = 0; i < Constant.REGISTER_INFOS.length; i++) {
if (Constant.REGISTER_INFOS[i].info == "") {
text = text + Constant.REGISTER_INFOS[i].title.toLowerCase() + ", ";
}
}
alert(text);
},
usernameValidate() {
if (Constant.REGISTER_INFOS[0].info.length < 4) {
alert("Username is too short");
return false;
}
},
Assuming that this is part of a Vue app, so something like:
const App = new Vue({
methods: {
onSubmit() {
var text = "Please insert ";
for (let i = 0; i < Constant.REGISTER_INFOS.length; i++) {
if (Constant.REGISTER_INFOS[i].info == "") {
text = text + Constant.REGISTER_INFOS[i].title.toLowerCase() + ", ";
}
}
alert(text);
},
usernameValidate() {
if (Constant.REGISTER_INFOS[0].info.length < 4) {
alert("Username is too short");
return false;
}
},
}
});
Then you want to call another method using the this keyword, to access other methods on this Vue instance.
So onSubmit() might look like:
onSubmit() {
var text = "Please insert ";
for (let i = 0; i < Constant.REGISTER_INFOS.length; i++) {
if (Constant.REGISTER_INFOS[i].info == "") {
text = text + Constant.REGISTER_INFOS[i].title.toLowerCase() + ", ";
}
}
this.usernameValidate();
alert(text);
},
There are some big issues with this code though, and that won't actually do anything of note, as nothing is being done with the return value.
A better way to handle this would be to:
Return true or false from usernameValidate, depending on whether or not it's successful, and check it in if statement.
Change the signature of the usernameValidate method to take an argument. This means that we can re-use this functionality with any input, making it a lot more flexible.
With these two changes, we end up with the following:
const App = new Vue({
methods: {
onSubmit() {
var text = "Please insert ";
for (let i = 0; i < Constant.REGISTER_INFOS.length; i++) {
if (Constant.REGISTER_INFOS[i].info == "") {
text = text + Constant.REGISTER_INFOS[i].title.toLowerCase() + ", ";
}
}
if (this.usernameValidate(Constant.REGISTER_INFOS[0].info) {
alert(text);
return true;
}
alert("Registration Failed!");
return false;
},
usernameValidate(username) {
if (username.length < 4) {
alert("Username is too short");
return false;
}
return true;
},
}
});
Hopefully that clears a few things up, and can give you a little more insight in to programming in general.
Having said all of that, I would highly recommend learning JavaScript from scratch, before getting stuck in to frameworks (which VueJS is) and things like that. Understanding the core principles of programming, conditional logic, etc., will make you much more competent in the long run, and just grabbing at code snippets from StackOverflow will just lead to you pulling your hair out, and being stuck on a problem for days at a time.
I am getting values from a model, but while checking the values it always goes in to the else part of the conditions. I am alerting the values I am getting and they are correct, but in the if condition it doesn't get satisfied. I even tried with ===.
$(document).ready(function() {
var mark = new Boolean(#Model.isMarketing);
var revenue = new Boolean(#Model.isRevenue);
var staff = new Boolean(#Model.isStaff);
if (revenue == true) {
$("input[name=isRevenue][value='isRevenue']").prop("checked", true);
} else if (staff == true) {
$("input[name=isRevenue][value='isStaff']").prop("checked", true);
} else if (mark === true) {
$("input[name=isRevenue][value='isMarketing']").prop("checked", true);
} else {
$("input[name=isRevenue][value='None']").prop("checked", true);
}
});
I assume that you're getting not true or "true" from #Model.isMarketing, #Model.isRevenue etc.
And never use the === in condition when you using new Boolean(true) it won't equal true with using ===.
I wanna suggest you several approaches:
1. Use !! instead of new Boolean(#Model.isMarketing);
e.g.
var mark = !!#Model.isMarketing;
2. Just remove new Boolean() and use if like:
var mark = #Model.isMarketing;
if(mark) {
//do smth.
}
else {
//do smth else
};
Also I wanna suggest how to improve your code.
$(document).ready(function () {
var trueMark = 'True';
var mark = trueMark === #Model.isMarketing;
var revenue = trueMark === #Model.isRevenue;
var staff = trueMark === #Model.isStaff;
var value = 'None';
if (revenue) {
value = 'isRevenue';
}
else if (staff) {
value = 'isStaff';
}
else if (mark) {
value = 'isMarketing';
}
$("input[name=isRevenue][value="+ value + "]").prop("checked", true);
});
Please, make sure that you're getting right values from #Model
I have a simple form which users can enter a "tweet". I ahve some javascript behind the scenes to control what happens when a url is entered.
If a url is entered such as test.com then a new input field will appear.
If a url that is stored in an array is entered, it will and the new input field along with a select option.
here is my javascript:
var test = ["test1.com", "test2.com", "test3.com"];
$('#tweet_text_ga').hide();
$('#custom_alias').hide();
$('#tweet_campaign').hide();
$('#tweet_text').keydown(function () {
var val = this.value;
if (/\.[a-zA-Z]{2,3}/ig.test(val)) {
$('#custom_alias').show();
} else {
$('#custom_alias').hide();
}
if ($.inArray(val, test) !== -1) {
$('#tweet_campaign').show();
} else {
$('#tweet_campaign').hide();
}
});
It works fine if just a url is entered. But as soon as you add more text, it disregards if the url is in the array, and removes the select option. I'm not quite sure on how to explain this any better, so i have setup a fiddle to show what i mean.
I hope someone understands and can point me in the right direction
Fiddle
That's because you are checking if a whole input is in the array: if ($.inArray(val, test) !== -1). You need to retrieve URL from the input using a regex and check that.
Write a regex that retrieves any URL, get that URL and check if it's one of your lucky ones:
var urlsInInput = /[a-z0-9]+\.[a-zA-Z]{2,3}/ig.exec(val);
if (urlsInInput.length == 1 && $.inArray(urlsInInput[0], test) !== -1) {
instead of
if ($.inArray(val, test) !== -1) {
Fiddle
Here is my version handling the first url
Live Demo
$('#tweet_text').keydown(function () {
var val = this.value;
var urls = val.match(/[a-z0-9]+\.[a-zA-Z]{2,}/ig);
var alias = (urls && urls.length>0)
$('#custom_alias').toggle(alias);
var tweet = urls && urls.length>0 && $.inArray(urls[0], test) !== -1;
$('#tweet_campaign').toggle(tweet);
});
What #siledh said. Here is how you could use your current test array
var reg = new RexExp(test.join('|').replace(/\./ig, "\\."), 'ig')
if( reg.test(val) ) {
$('#tweet_campaign').show();
} else {
$('#tweet_campaign').hide();
}
The reason the campaign field begins to disappear again is that you compare the whole value of the input with the array. If you just find all domain matches and then compare them to your array it should work.
Like so:
var test = ["test1.com", "test2.com", "test3.com"];
$('#tweet_text_ga').hide();
$('#custom_alias').hide();
$('#tweet_campaign').hide();
$('#tweet_text').keyup(function () {
var alias = false;
var campaign = false;
var domain = /([a-z0-9]+(:?[\-\.]{1}[a-z0-9]+)*\.[a-z]{2,6})/ig;
var val = this.value;
var match = val.match(domain);
if (match) {
alias = true;
match.forEach(function(e) {
campaign = campaign || ($.inArray(e, test) !== -1);
});
}
if (alias === true) {
$('#custom_alias').show();
} else {
$('#custom_alias').hide();
}
if (campaign === true) {
$('#tweet_campaign').show();
} else {
$('#tweet_campaign').hide();
}
});
Something wrong with your $.isArray(val, test), the value you use is the whole value.
And not sure your purpose, so write a code like this. hope it would help.
http://jsfiddle.net/sheldon_w/KLuK8/
var test = ["test1.com", "test2.com", "test3.com"];
var urlReg = /[^\s]+\.[a-zA-Z]{2,3}/ig;
$('#tweet_text_ga').hide();
$('#custom_alias').hide();
$('#tweet_campaign').hide();
$('#tweet_text').keydown(function () {
var val = this.value;
var matchedUrls = [];
val.replace(urlReg, function (matched) {
matchedUrls.push(matched);
});
if (matchedUrls.length > 0) {
$('#custom_alias').show();
} else {
$('#custom_alias').hide();
}
$(matchedUrls).each(function (idx, url) {
if ($.inArray(url, test) !== -1) {
$('#tweet_campaign').show();
return false;
} else {
$('#tweet_campaign').hide();
}
});
});
I have been looking at this code for too long and just can't see what I am missing. The error states that there is a syntax error on the very last line, I have checked all of my braces but cannot seem to find it. Can anyone help me to find it?
window.addEvent('domready', function() {
// Get the form
var form = $('comments_form');
// if the form is found...
if (form) {
// obtain error fields
var aname = $('accountname');
var anumber = $('accountnumber');
var cname = $('cardname');
var cnumber = $('cardnumber');
var security = $('securitycode');
var zip = $('zipcode');
// Set the default status
var isValid = true;
// input error function for the error messages
var addError = function (field, msg) {
field.addClass('error'); // Add error class to field
var error = field.getParent().getElement('span') || new Element('span', {'class': 'error'}); // add error message if not already placed
error.set('text', msg); // error text msg
error.inject(field, 'after'); // Insert error message after field
};
// detach error function used to delete any error messages and remove the error class
var removeError = function (field) {
field.removeClass('error'); // Remove error class from form fields
var error = field.getParent().getElement('span'); // find any existing error messages
// destroy if error message
if (error) {
error.destroy();
}
};
// insert submit form event
form.addEvent('submit', function (e) {
// Test name length
if (aname.get('value').length === 0) {
isValid = false;
addError(name, accountnameError);
} else {
isValid = true;
removeError(aname);
}
form.addEvent('submit', function (e) {
// Test name length
if (anumber.get('value').length === 0) {
isValid = false;
addError(anumber, accountnumberError);
} else {
isValid = true;
removeError(accountnumber);
}
form.addEvent('submit', function (e) {
// Test name length
if (cname.get('value').length === 0) {
isValid = false;
addError(cname, nameError);
} else {
isValid = true;
removeError(cname);
}
form.addEvent('submit', function (e) {
// Test name length
if (cnumber.get('value').length === 0) {
isValid = false;
addError(cnumber, numberError);
} else {
isValid = true;
removeError(cname);
}
form.addEvent('submit', function (e) {
// Test name length
if (securitycode.get('value').length === 0) {
isValid = false;
addError(securitycode, securityError);
} else {
isValid = true;
removeError(securitycode);
}
form.addEvent('submit', function (e) {
// Test name length
if (zipcode.get('value').length === 0) {
isValid = false;
addError(zipcode, zipError);
} else {
isValid = true;
removeError(zipcode);
}
// If form invalid then stop event happening
if (!isValid) {
e.stop();
}
});
}
});
You're missing the end curly brace and closing paranthesis for each form.addEvent('submit', function (e) {. Also, you could combine them into a single handler. Using a beautifier helps you easily find if these types of syntax errors.
Example for one of them
form.addEvent('submit', function (e) {
// Test name length
if (aname.get('value').length === 0) {
isValid = false;
addError(name, accountnameError);
} else {
isValid = true;
removeError(aname);
}
}); // <- you don't have that
On a side note, your var aname = $('accountname'); (and subsequent lines) look wrong. You probably mean to select it by id; use $('#accountname'). And I'm not aware of any addEvent function. I'm assuming you're using some other library, but for reference with jQuery you should use .on(event, handler)
I have JavaScript form validation functions like so:
function validate_name(field)
{
if (field == "") return "Please enter the name.\n";
return "";
}
function validate_specialty(field)
{
if (field == "") return "Please enter the specialty.\n";
return "";
}
function validate_location(field)
{
if (field == "") return "Don't forget the location.\n";
return "";
}
where the function that is called from the form's onSubmit is:
function validate_fields(form)
{
fail = validate_name(form.name.value);
fail += validate_specialty(form.specialty.value);
fail += validate_location(form.location.value);
if (fail == "")
return true;
else
{
alert(fail);
return false;
}
}
This works fine but I have decided that I don't want all three to necessarily be required. It would be great if I could make these three optional, such that if any one of these fields is filled in, it would validate true, but if all three fields are empty, I could throw an alert and validate false.
Any help is much appreciated.
You can do that by capturing the results separately, and testing with an OR grouping.
function validate_fields(form)
{
fail1 = validate_name(form.name.value);
fail2 = validate_specialty(form.specialty.value);
fail3 = validate_location(form.location.value);
if (fail1 == "" || fail2 == "" || fail3 == "")
return true;
else
{
alert(fail1 + fail2 + fail3);
return false;
}
}