prajeesh
prajeesh

Reputation: 2392

Conditional validation using single piece of code - AngularJS

The code contains two functions. First one is defined as follows

scope.validateContactName = function() {
    scope.address.invalidName = false;
    if (!scope.address.name) {
      scope.address.invalidName = true;
    }
}

which is invoked by the function validateContactName();

Now i have another function

scope.validateContactPhone = function() {
    scope.address.invalidPhone = false;
    if (!scope.address.phone) {
      scope.address.invalidPhone = true;
    }
}

which is invoked by the function validateContactPhone();

Instead of two functions, is there a way i can use a single function and do conditional validation?

Something like

validateContactInfo('name');

function validateContactInfo(attr) {
   //do validation based on the attribute
   // There is only one single piece of code for both conditions
}

Upvotes: 3

Views: 90

Answers (3)

Bilal Alam
Bilal Alam

Reputation: 894

Assuming contact information is used in a form to get input from the user. I would recommend to use angular's own form validation

If it is not the case, here is a generic way of checking if values exists in a object. Which you can add in project''s utilities

const contactInfo = {
name: 'My name',
phone: '123123123',
address: ''
}

function validateExistence(obj){
  const emptyKeys = [];
  for(let key in obj){
    if(!obj[key]) emptyKeys.push(key)
  }
  return emptyKeys
}

console.log(validateExistence(contactInfo));

Upvotes: 0

Frank Waalkens
Frank Waalkens

Reputation: 269

I would suggest something like this(ES6):

scope.address = [
	{
		type: "phone",
		invalid: false
	},
	{
		type: "name",
		invalid: false
	}
];

const validate = type => {

	let data = scope.address.find(a => a.type === type);

	if(!data.type) {
		data.invalid = true;
	}
};


validate("phone");
validate("name");

Upvotes: 0

Clarity
Clarity

Reputation: 10873

Maybe smth like this could work:

scope.validateField = function(field, errorField) {
  scope.address[errorField] = false;
  if (!scope.address[field]) {
    scope.address[errorField] = true;
  }
}

Or a shorter version:

scope.validateField = function(field, errorField) {
  scope.address[errorField] = !scope.address[field];
}

Upvotes: 2

Related Questions