Display validation messages when a button is clicked

痴心易碎 提交于 2019-12-11 04:46:04

问题


I think what I want to achieve is quite simple. Let's have a form with a required field, a select for instance (I've also tried it with an input and it's exactly the same situation anyway).

I want to display the ng-messages only when a button is clicked. If the form field was touched before clicking the button, it works fine. But I cannot do it if the form field is $untouched.

I've solved it setting programatically $touched to the form field, but I'm wondering if there is any way to solve it without this uggly 'hack'.

// Any way to avoid this line??
$scope.myForm.favoriteColor.$setTouched();
//

Code for reference:

HTML:

<md-input-container>
    <label>Favorite Color</label>
    <md-select name="favoriteColor" ng-model="favoriteColor" required>
      <md-option value="red">Red</md-option>
      <md-option value="blue">Blue</md-option>
    </md-select>
    <div class="errors" ng-messages="myForm.favoriteColor.$error" ng-show="validateWithHack">
      <div ng-message="required">Required</div>
    </div>
</md-input-container>

JS:

$scope.validateWithHack = function() {
  if ($scope.myForm.$valid) {
    alert('Form is valid.');
  } else {
    // Any way to avoid this line??
    $scope.myForm.favoriteColor.$setTouched();
    //
    $scope.validateWithHack = true;
  }
};

I'm pretty sure that this was working with previous versions of angular-material. Now I'm using the latest 1.1.1.

Here is a plunker where the problem can be easily reproduced.

Thanks in advance.


回答1:


Check the CodePen

I have added novalidate to your form and added type="submit" to your md-button

Edit 2: The type="submit" button actually triggers a form submit and so the angular form validates itself first, What we need to do is to prevent the submit and just do the validation.

novalidate(Just to supress the HTML5 validation) to your form and added type="submit" to your md-button : This Will Validate the form and submit the form, To validate and prevent form submit add ng-click="submitMethod(<yourForm>, $event)" to the <md-button> and define method as

$scope.submitMethod(form,ev){
  ev.preventDefault();
  //rest of your form work say if you want to do ajax or anything you like
  //check if form valid using form.$invalid
}


来源:https://stackoverflow.com/questions/39645748/display-validation-messages-when-a-button-is-clicked

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!