Make a field mandatory only if it is visible?

Make a field mandatory only if it is visible?

In some instances a field will only be shown if it is required. Is it possible to set it as mandatory only  if  it is made visible?
Can the mandatory attribute be scripted?