如何检查输入字段是否为空

时间:2016-06-24 13:55:45

标签: html css angularjs

我需要检查输入字段是否为空。

我尝试了以下操作,但它无法正常工作。

JavaScript的:

if ($scope.currentUser.Login.length != 0) {
    console.log($scope.currentUser.login.length);
}

HTML:

<div class="cClearFloat cInputSpace">
    <input placeholder="login" ng-model="currentUser.login">
</div>

有人可以帮助我吗?

5 个答案:

答案 0 :(得分:1)

尝试:

if($scope.currentUser.login !== null && $scope.currentUser.login !== undefined && $scope.currentUser.login !== "") {
   // Do stuff
}

答案 1 :(得分:0)

如果这是一个始终需要的字段,您可以使用所需的方法。

class nTree:

    def initialize(self, hypercube_coordinates, depth=0):
        self.data = [] #holds the data - this tells if the node is empty or not
        self.children = [] 
        self.depth = depth
        self.hypercube = hypercube #coordinates 

    #a bit inefficient since we are theoretically visiting each node
    #can be optimized later
    def count_nodes_at_level(self, depth):
        count = 0
        for child in self.children:
            if child.depth == depth:
                count += child.count_nodes_at_level(self.depth)
            else:
                child.count_nodes_at_level(depth)
        return count

如果您想更具体,可以指定长度要求。

<form action="demo_form.asp">
  Username: <input type="text" name="usrname" required>
  <input type="submit">
</form>

答案 2 :(得分:0)

你有一个错字。您的模型指向<input pattern=".{5,10}" required title="5 to 10 characters"> ,而不是login。 为了安全起见,您希望在使用Login或其他表达式之前检查属性是否确实存在。

length

答案 3 :(得分:0)

这还不够吗? 你可以检查一下     if($scope.currentUser && $scope.currentUser.login)它不允许空格,如果要接受空白输入,可以检查长度。正如lexith所说,你绑定登录并检查登录。它们不是同一个属性。

&#13;
&#13;
angular.module('myModule', []);

angular.module("myModule")
  .controller("DemoCtrl", demoCtrl);

demoCtrl.$inject = ["$scope"];
//demoCtrl
function demoCtrl($scope) {
  
  $scope.check = function(){
    if($scope.currentUser && $scope.currentUser.login){
    console.log($scope.currentUser.login);
    }
    else{
      console.log("there is no login");
    }
  }
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<html>
  <head>
    <title>AngularJS test</title>
  </head>
  <body data-ng-app="myModule">
    <div data-ng-controller="DemoCtrl as demoCtrl" >
      <div class="cClearFloat cInputSpace">
                    <input placeholder="login" ng-model="currentUser.login">
                </div>
      <button ng-click="check()">check</button>
    </div>
</body>
</html>
&#13;
&#13;
&#13;

答案 4 :(得分:-1)

像这样添加required

<div class="cClearFloat cInputSpace">
   <input placeholder="login" ng-model="currentUser.login" required>
</div>

如果它为空,则浏览器通知用户。

  1. 在控制器中查看:
  2. if ($scope.currentUser.Login.length =="undefined") { console.log($scope.currentUser.login.length); }

    快乐编码。

相关问题