AngularJS - prevent submissions of form with requi

2019-08-09 07:19发布

I have an AngularJS Form with 3 required fields inside (using ng-required). Without touching anything on the form and just simply pressing the 'Submit' button (ng-click="submit"), how do I trigger validation for the required fields AND prevent form submission? I've tried doing:

ng-required="form.$submitted && !firstName"

which triggers the validation, but also submits the form even though the form is technically $invalid??

3条回答
SAY GOODBYE
2楼-- · 2019-08-09 07:55

Since you mention that you are doing validation for individual elements and don't know to check whether the entire form is valid or not. You can use the following condition to check whether the form is valid or not

$scope.yourFormName.$valid

Use the above condition to check whether the form is valid or not. The above condition will become true only when all the required validations inside the form are valid. Hope this is what you're looking for

查看更多
混吃等死
3楼-- · 2019-08-09 08:08

I used the ng-submit directive as it triggers form.$submitted and validates ng-required fields properly before submitting.

For the case where you have multiple buttons, for I added an ng-click to each button and simply changed a $scope variable (e.g. $scope.pressedBtn). In the function that ng-submit points to, you could do something like:

if ($scope.pressedBtn === 'button1') {
    // submit
}
else if ($scope.pressedBtn === 'button2') {
    // save
}
查看更多
来,给爷笑一个
4楼-- · 2019-08-09 08:12

I would take a look at angular-validator: https://github.com/turinggroup/angular-validator. It is quite useful and really leans out your validation code. ng-Message is nice but you end up maintaining more HTML and therefore it seems it would be more watches.

  <form name="categoryForm" id="categoryForm" class="smart-form" angular-validator angular-validator-submit="save(true)" novalidate autocomplete="off">
      <fieldset>
        <section ng-class="{ 'has-error' : categoryForm.title.$invalid}">
          <label class="label">Title</label>
          <label class="input">
            <input name="title" type="text" ng-model="category.title" id="title" placeholder="Title" required
                   validate-on="dirty" required-message="'Title is required'">
          </label>
        </section>
        <section ng-if="isAdmin()">
          <div class="row">
            <section class="col col-6" >
              <label class="checkbox">
                <input type="checkbox" name="checkbox" ng-model="category.isGlobal">
                <i></i><span>Global</span></label>
            </section>
          </div>
        </section>
      </fieldset>
      <footer>
        <button  type="submit" class="btn btn-primary" ng-disabled="(categoryForm.$dirty && categoryForm.$invalid) || categoryForm.$pristine">
          Submit
        </button>
      </footer>
    </form>
查看更多
登录 后发表回答