How can I simplify form validation?

前端 未结 11 1499
[愿得一人]
[愿得一人] 2020-12-14 00:57

The code below seems to work pretty well for doing basic required form validation.

The form displays a red Name is required message when the field is dirty

11条回答
  •  死守一世寂寞
    2020-12-14 01:58

    One way you could do it is to abstract your validation expression to scope methods:

    PLUNKER

    HTML

    Name is required Great!

    Controller

    function Ctrl($scope) {
      $scope.isInvalid = function(field){
        return $scope.myForm[field].$invalid && $scope.myForm[field].$dirty;
      };
    
      $scope.isValid = function(field){
        return $scope.myForm[field].$valid && $scope.myForm[field].$dirty;
      };
    
    }
    

提交回复
热议问题