How to make a jQuery input validation function work with Angular templates?

169 Views Asked by At

I am using a jQuery function to auto-process forms, and show errors just as they occur using jQuery. I am also using Bootstrap 3.

(function() {
    // Form Processing
    $('input').each(function() {
        var $this = $(this);
        $this.on('input', function() {
            if ($this.val().length === 0) {
                if ($this.attr('required')) {
                    $this
                        .parent('div.control-group')
                        .addClass('has-error')
                        .end()
                        .siblings('p.text-danger')
                        .empty()
                        .text('This field is required');
                } else {}
            } else {}
        });
    });
})();

Basically, this checks whether a field is required. If the field is not valid, a simple error message is displayed. It works really nicely too.

Here's a basic template that makes this work:

<div class="control-group>
    <input type="email" required>
    <p class="text-danger"></p>
</div> 

However, when I am using Angular templates, the code does not occur, as the DOM is not loaded before hand. I think the right course to action would be to create an Angular directive for this code. I have a few questions regarding that:

  • Where do I put the derivative? Should it be something like myapp.run?
  • Am I wrong in my assumption of creating a derivative? Is there a better way to do this so that it works with Angular?

Thanks.

1

There are 1 best solutions below

1
On BEST ANSWER

You can use form or ng-form directive combined with ng-messages directive to avoid mixing jquery with angular

Example

<form name="myForm">
  <label>
    Enter your name:
    <input type="text"
           name="myName"
           ng-model="name"
           ng-minlength="5"
           ng-maxlength="20"
           required />
  </label>
  <pre>myForm.myName.$error = {{ myForm.myName.$error | json }}</pre>

  <div ng-messages="myForm.myName.$error" style="color:maroon" role="alert">
    <div ng-message="required">You did not enter a field</div>
    <div ng-message="minlength">Your field is too short</div>
    <div ng-message="maxlength">Your field is too long</div>
  </div>
</form>

Source https://docs.angularjs.org/api/ngMessages/directive/ngMessages