javascriptformsangularjsvalidationdirty-data

AngularJS - set form pristine without removing validation errors


We have an autosave and an explicit save for a particular form (it's a long form, and we don't want the user to lose data). For an explicit save, invalid data will block the save from occurring and an XHR will not be sent back to the server. However, for the autosave, we want the data to be saved (if possible) regardless of front-end validation.

What we need to have happen is, if the save is successful on the backend, the front-end should mark the form as no longer being dirty. But... and here's the sticker - it should not remove any validation errors/error messages from the form.

From what I'm seeing (or at least from what I understand), .$setPristine() will un-dirty the form, but it will, problematically, also remove validation errors.

Is there a way to un-dirty the form without removing the validation errors so that the autosave doesn't run when it's already performed a save, but so that the user still has the feedback of which fields are invalid so that they can fix the issues?

Thanks!


Solution

  • A form's $pristine/$dirty states are not connected to the $valid/$invalid states. Your error messages shouldn't be removed (unless you use $pristine/$dirty in the condition that shows/hides the messages).


    So, you can call the FormController's $setPristine() method in your autosave function, which will "un-dirty" the form, but will not affect the validation and error messages.


    See, also, this short demo.

    E.g.:
    * In the fiddle above, enter something in one field (so it becomes valid and the form becomes dirty).
    * The Save button gets enabled.
    * Pressing the Save button sets the form's state to $pristine, so the button gets disabled (this simulates the autosave).
    * The errors messages are still visible though (and the form's validity state does not change).