angular js:无法验证textarea

时间:2016-06-22 08:52:13

标签: angularjs validation textarea

家伙!

我正在尝试点击链接时验证文本区域。事情是,它不会进入一个形式。当用户点击链接时,应该发布在文本区域中输入的内容(保存到数据库)。

我为此写了一个验证。不幸的是,它不起作用,我可以发空白帖子。我试图阻止发布空白帖子。我在小提琴中重新创建了表单和控制器。链接我会提供。但在此之前,请看一下我的html和js代码。

HTML

<div ng-app="myApp" ng-controller="myMap">
  <div class="post-textarea" ng-class="{ 'has-error': vm.currentPost.content.$dirty && vm.currentPost.content.$error.required }">
    <textarea class="form-control" rows="3" ng-model="vm.currentPost.content" required></textarea>
    <a ng-click="vm.addPost(vm.currentPost.content,vm.currentPost.$valid)">Clik to Post and validate</a>
  </div>
</div>

JavaScript

angular.module('myApp', [])
  .factory('myService', function($http) {
    var baseUrl = 'api/';
    return {
      postCurrentPost: function(newPost) {
        var dataPost = {
          newPost: newPost
        };
        return $http({
          method: 'post',
          url: baseUrl + 'postCurrentPost',
          data: dataPost,
          headers: {
            'Content-Type': 'application/x-www-form-urlencoded'
          }
        });
      }
    };

  })
  .controller('myMap', function(myService, $http, $scope) {

    var vm = this;
    var userObject;

    // Add a post
    vm.addPost = function(newPost, isValid) {
      if (isValid) {
        var currentPost = vm.currentPost;
        currentPost.content = ""; //clear post textarea
        myService.postCurrentPost(newPost).success(function(data) {
          vm.posts = data;
        });
      } else {
        alert('Validation not working');
      }
    };
    //Check validation
    $scope.getError = function(error, name) {
      if (angular.isDefined(error)) {
        if (error.required && name == 'vm.currentPost.content') {
          return "This field is required";
        }
      }
    }
  });

这是一个FIDDLE

1 个答案:

答案 0 :(得分:0)

应使用表单输入元素的名称而不是模型值。

https://docs.angularjs.org/api/ng/directive/form

<div ng-app="myApp" ng-controller="myMap">
    <form name="formContent">
      <div class="post-textarea" ng-class="{ 'has-error': formContent.content.$dirty && formContent.content.$error.required }">
      <textarea name='content' class="form-control" rows="3" ng-model="vm.currentPost.content" required></textarea>
      <a ng-click="vm.addPost(vm.currentPost.content,vm.currentPost.$valid)">Clik to Post and validate</a>
      </div>
    </form>
    Content is dirty: {{formContent.content.$dirty}}
    <br>
    Content has required: {{formContent.content.$error.required}}
</div>