I am new to Salesforce and need help in writing a validation rule. I have a Master object that can have multiple child objects.The child object has a field 'Type' with value lets say X and Y. If one record of type X is saved and related to the Master object , then thereafter only child object of type X can be tagged to that single master object. If first object saved is of Y type, then next objects tagged to that single master object can be of Y type only. I thought of applying validation rule but that has to be applied after first object creation and the type field of child object is to be validated thereafter. I am stuck at this. What approach can i take?
I suggest first create a custom field on the master object: permitted type. Then, using process builder or workflow, this field must be filled when a child object is created, but only if it has not been filled already.
And then you can create a validation rule: error when permitted type of master object is not empty and type (of child object) is not equal to permitted type of master object.
This cannot be accomplished with validation rules alone. Validation rules cannot traverse down the relationship hierarchy (i.e. from your Master record to all (or any) of the Detail records). Neither can formula fields or workflow rules.
before insert trigger would be able to do what you want (because you could use a query to get at the other Detail records, and then inspect them to see whether the new Detail record matches the other Detail record(s)).
Other than that, you may be able to use a combination of a rollup summary field (to get data from your Detail records to the Master record) and a validation rule (on the Detail record).
The important thing that you should take away from this is that you need to keep in mind where your data is, and where you need it to be. In this situation, you have data on the Detail records that needs to somehow be present on the Master record so that you can make a decision (is this new Detail record valid or not?)