Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If/else condition inside an Object

Tags:

javascript

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)

like image 852
John Cooper Avatar asked Dec 04 '22 08:12

John Cooper


2 Answers

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()).

like image 55
Gabi Purcaru Avatar answered Dec 17 '22 11:12

Gabi Purcaru


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.

like image 22
Lightness Races in Orbit Avatar answered Dec 17 '22 10:12

Lightness Races in Orbit