Reputation: 7631
function Validator(formIsValid) {
if(this.formIsValid) {
alert('Form is valid!');
}
else {
alert('Form is invalid...');
}
}
Validator.prototype = { // Notice the .prototype here, it's important!
formIsValid: true,
enforceTextFieldMinLength: function(field, minLength) {
if (!field.value || field.value.length < minLength) {
this.formIsValid = false;
}
},
enforceLabelHasText: function(label) {
if (!label.text) {
this.formIsValid = false;
}
}
}
//var val = new Validator();
The above is my Val.js. This is how i am using in my otherFile.js
AddPatient.Firstname = FirstNameValue || Validator.enforceLabelHasText(FirstName);
I get an error saying cannot find function enforceLabelHasText in Object function Validator(formIsValid)
Upvotes: 4
Views: 18899
Reputation: 41
You can insert logic into an object literal, using an iife. Like this;
const testable = 1
const obj = {
a: 'value1',
b: (() => {
if (testable === 1) {
return 'testable was 1'
} else {
return 'testable was not 1'
}
})()
}
console.log(obj)
Upvotes: 4
Reputation: 31524
You can't put expressions in an object definition. If you want code to be executed after an object instance is created, you should use:
function Validator() {
if(this.formIsValid) {
alert('Form is valid!');
}
else {
alert('Form is invalid...');
}
}
Validator.prototype = { // Notice the .prototype here, it's important!
formIsValid: true,
enforceTextFieldMinLength: function(field, minLength) {
if (!field.value || field.value.length < minLength) {
this.formIsValid = false;
}
},
enforceLabelHasText: function(label) {
if (!label.text) {
this.formIsValid = false;
}
}
}
var a = new Validator();
This is a dummy solution; you will want to add arguments to the Validator()
function, to initialize formIsValid
and the other values. I suggest you should read the MDC's description on prototypes.
EDIT: If you went with the prototype solution, you need to call val.enforceLabelHasText(FirstName)
, after making val
a global variable (either by omitting the var
or by using var window.val = new Validator()
).
Upvotes: 5
Reputation: 490173
Validator
is an object literal and you can only assign properties there, not arbitrary code.
You could assign a function which includes your code to a property.
Upvotes: 2
Reputation: 385114
This is not valid syntax.
You've dumped an if/else
condition inside an object definition, like this:
var myObj = { a, b, c, d,
if (true) {
alert('WTF!');
}
};
Procedural code like this must be inside a function.
Upvotes: 5
Reputation: 10992
Bind this to a variable in the beginning.
var that = this;
This keeps this changing and point to something else. And use firebug!
Upvotes: 1