Skip to content

Angular2 Forms Controls validation "OnLostFocus (OnBlur)" rather than "OnChange"  #7113

Closed

Description

@liquidboy

Hi,

Looking at the code for setting up form controls in shared.ts it appears we detect control changes onChange "registerOnChange"

eg. if a user types into an input control that is an ng2 angular control, each keypress triggers a validationcheck ..

It appears to be a big change if i were to change it from OnChange to something like LostFocus of the control ...

The reason i ask is business really doesn't like the validation messages appearing suddenly even while the user hasn't finished filling in the field ... eg. filling in a "Password" control, the user is suddenly shown validation errors while they're typing ...

Anyone got a nice solution for hiding validation messages and only showing them once they tab off the control ?!

Activity

  1. gbataille commented on Feb 17, 2016

    @gbataille
    Contributor

    That's interesting.
    So the class valid/dirty/invalid seems nice (I guess you can agree with the decorator that say the field is not yet compliant).
    However I agree that the messages are more cumbersome and sometimes obvious enough (like on a login screen)

    The problem is when to display them then? how to know the user is "done"

    For example I have a form that disables the submit button if the form is invalid. If it's the last field that is invalid, the user is editing it. He can't click on the button, so the "lost focus" event might not come depending on the user behaviour.

    Let me throw a couple of UX ideas that use form validation on each change, but that react a bit differently (async ?) to it:

    • display the errors/details after some timer of inactivity (a bit heavy)
    • display the errors/details in a way that does not disturb the form layout (in a side floating tooltip rather than in a div that appear/disappear below each input)

    what do you think?

  2. zoechi commented on Feb 17, 2016

    @zoechi
    Contributor

    I think the issue is just about being able to use the blur event instead of the change event for calling the validator, so validation is only done when the user is done editing a field.

    display the errors/details in a way that does not disturb the form layout (in a side floating tooltip rather than in a div that appear/disappear below each input)

    Shouldn't bee too hard. This is IMHO only a CSS problem not an Angular problem.

    display the errors/details after some timer of inactivity (a bit heavy)

    Shouldn't be too hard to implement. Just create an additional flag used in *ngIf to show/hide validation errors. Subscribe to form changes and if there is some delay toggle the flag.

    <div class="validation-message" *ngIf="form.controls['xxx'].isValid && isIdle">
    
  3. liquidboy commented on Feb 17, 2016

    @liquidboy
    Author

    thanks guys ... ill try out the recommendation from zoechi ...

    our interaction designers are very adamant that the UI should NOT be changing whilst the user is entering data .. apparently they hate any form of distraction for the user during their data entry interaction..

  4. ps2goat commented on Mar 17, 2016

    @ps2goat

    +1 to have the option to validate on blur vs on change. If blur, don't mark an input as dirty unless the value has changed and the user has moved focus out of the input.

  5. JohnnyClutch commented on May 24, 2016

    @JohnnyClutch

    The onBlur validation is definitely something I occasionally used in Angular 1, and will be implementing via a "controller" function if no provision is made by Angular 2. +1

  6. changed the title [-]Angular2 Forms Controls validation "OnLostFocus" rather than "OnChange" [/-] [+]Angular2 Forms Controls validation "OnLostFocus (OnBlur)" rather than "OnChange" [/+] on Jun 15, 2016
  7. bruceauyeung commented on Jul 15, 2016

    @bruceauyeung

    hi everyone !
    i wanna know whether this validate-onblur mechanism has been implemented in @angular/forms 0.2.0 ? if not, is there any workaround to do this ?

  8. BBegouin commented on Jul 19, 2016

    @BBegouin

    +1 :) any news of this feature ?

  9. AliHoussein commented on Aug 11, 2016

    @AliHoussein

    +1 interested as well!

  10. Cuel commented on Sep 28, 2016

    @Cuel
    Contributor

    Ran into this issue myself, would be nice if the form controls could report if their input is currently active/focused

  11. kara commented on Oct 13, 2016

    @kara
    Contributor

    @liquidboy If the concern is that the error messages are being displayed as the user types (too early), have you considered using the touched property? A control is only marked touched on the blur event, so the error message would not appear until then.

    <div class="error" *ngIf="email.touched && email.invalid".
       Email is invalid!
    </div>
    <input name="email" ngModel #email="ngModel"> 

    What we don't have yet is support for actually running the validation on blur instead of on value change. Besides error message display, what are some other use cases for this? Trying to get a read on priority.

  12. 78 remaining items

  13. marokac commented on Oct 24, 2017

    @marokac

    Thus because i been struggling with the sane issue here. maybe you can help. I am trying to validate a form using angular formBuilder..here is my code:

    ngOnInit() {
    this.formBuilder = new FormBuilder();
    this.simpleForm = this.formBuilder.group({
    notifyMeRadio: [],
    notifyMeEmail: [this.notifyMeEmail,[CommonValidators.isValidEmailAddress]],
    notifyMeSMS: [this.notifyMeSMS, [Validators.minLength(10)]],
    notifyMeFax: [this.notifyMeFax,[CommonValidators.isValidBeneficiaryName]],
    notifyBeneficiaryRadio: [''],
    notifyBeneficiaryEmail: [this.notifyBeneficiaryEmail,[CommonValidators.isValidEmailAddress]],
    notifyBeneficiarySMS: [this.notifyBeneficiarySMS,[Validators.minLength(10)]],
    notifyBeneficiaryFax: [this.notifyBeneficiaryFax,[Validators.minLength(10)]],
    });
    this.simpleForm.valueChanges.subscribe(data => this.onValueChanged(data));
    this.onValueChanged();

    And my validation messages object goes like this:

    validationMessages = {
    'notifyMeSMS': {'required':'field cannot be empty',
    'isValidEmailAddress':'10 digist'
    },
    'notifyMeEmail': {'required': 'Please enter valid Email address'},
    'notifyMeFax' : { 'required': 'Please enter valid Fax name',
    'isValidBeneficiaryName':'isValidBeneficiaryName'
    },

    'notifyBeneficiarySMS':  {'required':'Please enter valid
    

    SMS', 'isValidEmailAddress':'please type a valid email address'},
    'notifyBeneficiaryEmail': {'required':'required field'},
    'notifyBeneficiaryFax' : {'required':'Please enter valid beneficiary Fax'},
    };

    Form errors here:

    formErrors: {
    'notifyMeRadio':'',
    'notifyMeEmail': '',
    'notifyMeSMS': '',
    'notifyMeFax': ''
    },

    And finally my OnvalueChange method:

    onValueChanged(data?: any) {
    if (!this.simpleForm) { return; }
    const form = this.simpleForm;

    for (const field in this.formStatus.formErrors) {
    
      //this.formStatus.formErrors[this.formStatus.formErrors.notifyMeSMS] = ''
      this.formStatus.formErrors[field] = '';
      const control = form.get(field)
      if (control && control.dirty && !control.valid) {
        const messages = this.validationMessages[field];
        for (const key in control.errors) {
        this.formStatus.formErrors[field] +=messages[key] + ' '
       
        
        }
      }
    }
    

    }

    My issue here is i can only get validation messages when i include required and it only return required only

    please help guys

  14. marokac commented on Oct 24, 2017

    @marokac

    @notsonotso I will beg you on this one my man please help if you can...

  15. trotyl commented on Oct 24, 2017

    @trotyl
    Contributor

    @marokac GitHub issue is not used for support request, please refer to CONTRIBUTING for more information.

  16. marokac commented on Oct 24, 2017

    @marokac

    Point taken brah ..thanks any way

  17. rmcsharry commented on Feb 1, 2018

    @rmcsharry

    Validations firing onBlur appear to conflict with having a 'Cancel' button for the form. Cancel is not like a form reset, it is a 'total dismiss' of the input/edit operation, possibly even closing the form.

    If a field has focus, then the validation logic fires when the field loses focus and before the Cancel click occurs. This is particularly a bad UX when the form is inside a modal - since the Cancel button also should dismiss the modal, except it cannot because of the validation firing first.

    SO example here.

    I believe in Angular 1.x we could set form.submitted = false inside the Cancel click handler, but in Angular 2+ submitted is a read-only attribute and cannot be set.

    So how can we 'form cancel' without firing any validations?

  18. steelx commented on Apr 19, 2018

    @steelx

    this post should be awarded "most patient users ever"

  19. marokac commented on Apr 19, 2018

    @marokac

    Thank you

  20. jkrot commented on Apr 24, 2018

    @jkrot

    I would still like this as well because doing silly things with render to get this to happen doesn't make me happy.

  21. imadhy commented on Jul 4, 2018

    @imadhy

    updates ?

  22. spyro2000 commented on Jul 16, 2018

    @spyro2000

    Why isn't that just a global setting or something?

  23. SystemDisc commented on Aug 31, 2018

    @SystemDisc

    Someone come up with a solid proposal that we can agree on. Then, a PR can be made implementing that proposed solution.

  24. marokac commented on Aug 31, 2018

    @marokac

    I think we can fire the blur event only when click happens inside the form

  25. angular-automatic-lock-bot commented on Sep 14, 2019

    @angular-automatic-lock-bot

    This issue has been automatically locked due to inactivity.
    Please file a new issue if you are encountering a similar or related problem.

    Read more about our automatic conversation locking policy.

    This action has been performed automatically by a bot.

  26. locked and limited conversation to collaborators on Sep 14, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions