使用ng-change验证现有用户ID

时间:2017-11-24 06:04:10

标签: javascript angularjs

所以我正在尝试使用ng-change创建用户ID验证,问题是我认为我的if/else statement错了。因为有时候我的ng-class给了我错误的价值,以便在输入时工作,但是一旦输入被删除,它就会给我错误的值。

HTML

<div ng-class="{'has-success': vm.value == 'true', 'has-danger': vm.value == 'false'}">
     <input type="text" name="userId" class="form-control form-control-sm" ng-class="{'form-control-success': vm.value == 'true', 'form-control-danger': vm.value == 'false'}"
                placeholder="Username" ng-model="userData.userId" ng-change="vm.checkId(userData.userId)" ng-pattern="/^[a-zA-Z0-9]*$/" ng-minlength="5" ng-maxlength="14" required>
     <div ng-messages="regForm.userId.$error" class="colorValid" role="alert">
        <div ng-message="minlength">Your field is too short</div>
        <div ng-message="maxlength">Your field is too long</div>
       <div ng-message="pattern">Invalid Characters</div>
    </div>
 </div>

控制器

function checkId(data) {
    if (data) {
      return dataservice.getUser(data).then(function (data) { // get request
        if (data) {
          console.log('User-ID not available');
          vm.value = 'false';
        }else {
          vm.value = 'true';
          console.log(data);
          console.log('User-ID Available');
        }
      });
    } else {
      vm.value = 'null';
    }
}

感谢任何建议都受到欢迎。

2 个答案:

答案 0 :(得分:1)

首先,你为checkId参数和从API调用返回的数据使用相同的变量名,因此很难理解你的意图是什么。另外请澄清getUser()在'data'中返回的内容。

尝试对代码进行以下修改,同时添加对空字符串的检查,因为在用户删除该值后,它仍然设置但是它是空的。

function checkId(userData) {
  if (userData && userData!="") {
    return dataservice.getUser(userData).then(function (data) {
      if (data!="") {
        console.log('User-ID not available');
        vm.value = 'false';
      } else {
        vm.value = 'true';
        console.log(data);
        console.log('User-ID Available');
      }
    });
  } else {
    vm.value = 'null';
  }
}

答案 1 :(得分:1)

function checkId(userID) {
    if (userID != null) {
        return dataservice.getUser(userID).then(function(user) {
            if (user) {
                vm.value = false;
                console.log('User-ID not available');
            }else {
                vm.value = true;
                console.log('User-ID Available');
            }
        });
    } else {
      vm.value = false;
    }
}

并将您的HTML更改为:

<div ng-class="{ 'has-success': vm.value, 'has-danger': !vm.value }">
    <input type="text" name="userId" class="form-control form-control-sm" ng-class="{'form-control-success': vm.value, 'form-control-danger': !vm.value}" placeholder="Username" ng-model="userData.userId" ng-change="vm.checkId(userData.userId)" ng-pattern="/^[a-zA-Z0-9]*$/" ng-minlength="5" ng-maxlength="14" required>
     <div ng-messages="regForm.userId.$error" class="colorValid" role="alert">
        <div ng-message="minlength">Your field is too short</div>
        <div ng-message="maxlength">Your field is too long</div>
        <div ng-message="pattern">Invalid Characters</div>
    </div>
 </div>