Javascript file getting syntax error - javascript

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)

Related

How to check for already existing value and display an error message using C#, typescript file

Hi I am new to typescript. Blocked and couldn't move forward. Please help!
Below is my PartnerService.cs code to check for duplicates.
private bool CheckforDuplicateCrmIdOrName(string envCode, string crmId, string name)
{
bool partnerExists = false;
var allPartners = this.feeDataAccess.GetAllPartners(envCode).ToList();
var partnerByCrmId = allPartners.FirstOrDefault(p => !string.IsNullOrEmpty(p.CrmId) && p.CrmId.ToUpper() == crmId.ToUpper());
if (partnerByCrmId != null)
{
this.logService.Warn($"Cannot add the account {name} on environment {envCode}. An account with CRM Id {crmId} already exists.");
partnerExists = true;
}
var partnerByName = allPartners.FirstOrDefault(p => !string.IsNullOrEmpty(p.Name) && p.Name.ToUpper() == name.ToUpper());
if (partnerByName != null)
{
this.logService.Warn($"Cannot add the account {name} on environment {envCode}. An account with name {name} already exists.");
partnerExists = true;
}
return partnerExists;
}
Below is my typescript code (create-partner.ts), when I click on Save this method is called. And if there is any error - Error popup displays.
save() {
if (this.isLoading || !this.isValid()) {
return;
}
var dlg = this.modalService.confirm(`Partner ${this.newPartner.Name} will be created with a subscription containing ${this.nbOptionLicenseAdded + 1} license(s).`, 'Are you sure you would like to continue?');
dlg.then(() => {
this.isLoading = true;
this.partnerService.addPartner(this.newPartner, this.partnerLicenses, this.expirationDate)
.then((success: boolean) => {
if (success) {
this.modalService.notify(`Partner \"${this.newPartner.Name}\" has been created.`, `Succesful`);
this.cancel();
} else {
this.modalService.error(`An error has been occured in the creation of the partner \"${this.newPartner.Name}\". Please try later.`);
}
})
.catch(() => {
this.modalService.error(
`An error has been occured in the creation of the partner \"${this.newPartner.Name
}\". Please try later.`);
})
.finally(() => this.isLoading = false);
});
}
This is my PartnerService.ts where addPartner method is included.
addPartner(newPartner: Partner, subscriptionLicenses: FeLicense[], expirationDate: Date): angular.IPromise<boolean> {
var newSubscription = new FeSubscription();
newSubscription.Coupons = [];
subscriptionLicenses.forEach((license: FeLicense) => {
var newCoupon = new FeCoupon();
newCoupon.IsOption = license.IsOption;
newCoupon.LicenseCommercialRef = license.CommercialReference;
newCoupon.LicenseId = license.LicenseId;
if (expirationDate) {
var customDate = expirationDate.getFullYear() + '-' + (expirationDate.getMonth() + 1) + '-' + expirationDate.getDate();
newCoupon.ExpirationDate = customDate;
}
newSubscription.Coupons.push(newCoupon);
});
newPartner.Subscriptions = [];
newPartner.Subscriptions.push(newSubscription);
// Empty state is country is not US
if (newPartner.Address.CountryCode !== app.config.GlobalConstants.Default.usCountryCode) {
newPartner.Address.State = '';
}
return this.partnerWebService.addPartner(newPartner);
}
When I click on Save() button - I want to check for the existing CRMID and Name, If it already exists then it should return me a error message saying "CRMID already exists" or "Name already exists"

Form validation before POST Request

So I have 2 functions, one is a async function that is basically a HTTP Post Request, the other one is a form validation. I want the POST Request function to trigger only if the form validation function returns true. The form validation looks like this:
regForm.addEventListener('submit', function(event){
if (checkInputs()) {
// trigger post request function
}
})
function checkInputs() {
const usernameValue = form.username.value.trim();
const passwordValue = form.password.value.trim();
const emailValue = form.email.value.trim();
if (usernameValue === '') {
// trigger another function that handles errors
setError(form.username, 'Can\'t be blank');
} else {
// triggers function that handles success(color change, etc.)
setSuccess(form.username);
}
if (passwordValue=== '') {
// trigger another function that handles errors
setError(form.password, 'Can\'t be blank');
} else {
// triggers function that handles success(color change, etc.)
setSuccess(form.password);
}
}
But this doesn't seem to work, it doesn't trigger the POST Request function.
inside function checkInputs(), create a variable let check = true, assign false to this variable in every if statement:
if (usernameValue === '') {
setError()
check = false;
}
return check; at the end of function.
It triggers, because you don't return anything from the checkInputs function.
You need to return boolean /true or false/.
Something like:
function checkInputs() {
const usernameValue = form.username.value.trim();
const passwordValue = form.password.value.trim();
const emailValue = form.email.value.trim();
let check = true;
if (usernameValue === '') {
// trigger another function that handles errors
setError(form.username, 'Can\'t be blank');
check = false;
} else {
// triggers function that handles success(color change, etc.)
setSuccess(form.username);
}
if (passwordValue=== '') {
// trigger another function that handles errors
setError(form.password, 'Can\'t be blank');
check = false;
} else {
// triggers function that handles success(color change, etc.)
setSuccess(form.password);
}
return check;
}

jQuery - Checking if array is empty or has attributes

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 !== {})

Unable to validate a custom group using Knockout Validation

I cannot work out how to get the Knockout Validation plugin to validate a custom selection of viewmodel properties. I can call isValid() to validate the entire viewmodel successfully however.
I have followed the documentation set out here which covers the scenario and also checked all the answers I can find on stack overflow.
My code looks like this:
function MyViewModel() {
var self = this;
self.myproperty = ko.observableArray().extend({ minLength: { message: 'You must specify at least one item.'} })
self.anotherproperty = ko.observable().extend({ required: { params: true, message: 'You must supply a value.'} });
self.IsEntireModelValid = function() {
if (!self.isValid()) {
self.errors.showAllMessages();
return false;
}
else {
return true;
}
self.IsAnotherPropertyValidOnly = function() {
var errors = ko.validation.group(self.anotherproperty);
if (errors.length > 0) {
errors.showAllMessages();
return false;
}
else {
return true;
}
}
When I call self.IsAnotherPropertyValidOnly() the errors variable contains no errors, but when I call self.IsEntireModelValid() I get the correct response.
Could someone point out what I'm doing wrong?
You need to use errors().length.
self.IsAnotherPropertyValidOnly = function() {
var errors = ko.validation.group(self.anotherproperty);
if (errors().length > 0) {
errors.showAllMessages();
return false;
}
else {
return true;
}
}
http://jsfiddle.net/WY7V3/2/

Why isn't this working javascript?

I am using this to detect errors on my form...
var error = false;
if (val === '') {
error = true;
}
if (error = true) {
$('#joinForm .submit').click(function(event) {
event.preventDefault();
});
}
Simple really but not working, am I missing something stupid? variable error is default false.
If an error is found it is true.
If error is found to be true it prevents the form being submitted?
var error = false;
if (val === '') { // <<< This checks type first, then value
// An empty '' variable is not type-equivalent
// to a (boolean) false value
error = true;
}
if (error = true) { // <<< You're setting a variable here, which means
// means that you're testing if the variable
// assignment itself is successful, you'll get
// a true result in most cases, and except with
// things like while loops, you shouldn't use this
// form.
// Maybe you want == (falsy)? Or === (type-checked)?
$('#joinForm .submit').click(function(event) {
event.preventDefault();
});
}
You should do the checking in the submit event handler:
$('#joinForm').submit(function(event) {
var error = false;
if (val === '') {
error = true;
}
if (error) {
event.preventDefault();
}
});

Categories