如何在angularjs中使用$ asyncValidators并在HTML中设置警告消息

时间:2017-06-22 14:12:29

标签: javascript angularjs angular-promise

这是我的第一个更大的表格,带有验证等。 我已经创建了一个注册表单,我正在使用ng-messages进行验证。问题是我需要验证用户名,它是否已存在于我们正在使用或可用的JSON服务器中。当然,如果在用户输入的HTML中弹出警告,如果它可用,则不再禁用提交按钮(因为表单将是$ valid)并且用户可以注册。我想使用 angular-sanitize ,因为我发现了这个(我不知道它们是否相关):

    ngModel.$asyncValidators.uniqueUsername = function(modelValue, viewValue) {
      var value = modelValue || viewValue;

      // Lookup user by username
      return $http.get('/api/users/' + value).
         then(function resolved() {
           //username exists, this means validation fails
           return $q.reject('exists');
         }, function rejected() {
           //username does not exist, therefore this validation passes
           return true;
         });
    };

以下是我现在使用的代码(注册表单,控制器和服务):

// Controller:
export default class registerPageController {
  constructor(userService, authenticationService, $location) {
    this.register = "Register";
    this.userService = userService;
    this.$location = $location;
    this.authenticationService = authenticationService;
    this.hasLoggedIn = false;
  }

  onSubmit(user) {
    let self = this;
    let {
      name,
      age,
      email,
      username,
      password
    } = user;
    self.userService.register(name, age, email, username, password).then((res) => {
        self.userService.login(username, password).then(function (response) {
          let data = response.data;

          if (data.length) {
            let user = data[0];
            self.hasLoggedIn = true;
            self.authenticationService.setCredentials(username, password);
            self.$location.path('/');
          }
        });
      })
      .catch(err => {
        // WHAT TO PUT HERE AFTER THE USERNAME EXIST VALIDATION ?
      })
  }
}

// Service:

export class UserService {
  constructor($http) {
    this.$http = $http;
  }

  login(username, password) {
    return this.$http({
      method: 'GET',
      url: 'http://localhost:3000/users',
      params: {
        username: username,
        password: password
      }
    });
  }

  register(name, age, email, username, password) {
    return this.$http({
      method: 'POST',
      url: 'http://localhost:3000/users',
      data: {
        name: name,
        age: age,
        email: email,
        username: username,
        password: password
      }
    });
  }

// SHOULD I PUT HERE THE USERNAME EXIST VALIDATION LOGIC ?

}
<div class="container main-content">
  <form class="registrationForm" name="registerForm" ng-submit="register.onSubmit(register.user)" novalidate="novalidate">

    <!-- Enter Name -->
    <div class="form-group">
      <label for="name" class="control-label"><span id="reqInfo">*</span> Name</label>
      <input type="text" name="name" class="form-control" ng-model="register.user.name" ng-pattern="/[a-zA-Zа-яА-Я]+/" id="name"
        required="" placeholder="Example: Petar Petrov">
      <div ng-messages="registerForm.name.$error" ng-show="registerForm.name.$touched" style="color:maroon" role="alert">
        <div ng-message="required">Your name is required</div>
      </div>
    </div>

    <!-- User Age-->
    <div class="form-group">
      <label for="age" class="control-label"><span id="reqInfo">*</span> Age</label>
      <input type="number" name="age" class="form-control" ng-model="register.user.age" ng-min="18" min="18" id="age" required=""
        placeholder="Enter your age">
      <div ng-messages="registerForm.age.$error" ng-show="registerForm.age.$touched" style="color:maroon" role="alert">
        <div ng-message="min">You must be at leats 18 years old</div>
      </div>
    </div>

    <!-- Enter E-mail -->
    <div class="form-group">
      <label for="email" class="control-label"><span id="reqInfo">*</span> E-mail</label>
      <input type="email" name="email" class="form-control" ng-model="register.user.email" ng-pattern="/((([A-Za-z]{3,9}:(?:\/\/)?)(?:[\-;:&=\+\$,\w]+@)?[A-Za-z0-9\.\-]+|(?:www\.|[\-;:&=\+\$,\w]+@)[A-Za-z0-9\.\-]+)((?:\/[\+~%\/\.\w\-_]*)?\??(?:[\-\+=&;%@\.\w_]*)#?(?:[\.\!\/\\\w]*))?)/"
        id="email" required="" placeholder="Example: mail@mail.net">
      <div ng-messages="registerForm.email.$error" ng-show="registerForm.email.$touched" style="color:maroon" role="alert">
        <div ng-message="required">Your valid e-mail is required</div>
      </div>
      <br>

      <!-- Enter Username -->
      <div class="form-group">
        <label for="username" class="control-label"><span id="reqInfo">*</span> Username</label>
        <input type="text" name="username" ng-minlength="5" ng-maxlength="20" class="form-control" ng-model="register.user.username"
          ng-pattern="/^[A-Za-z0-9_]{1,32}$/" ng-minlength="7" id="username" required="" placeholder="Enter your username">     
        <div ng-messages="registerForm.username.$error" style="color:maroon" role="alert">
          <div ng-message="minlength">Your Username must be between 7 and 20 characters long</div>
        </div>
        <br>

        <!-- Enter Password -->
        <div class="form-group">
          <label for="password" class="control-label"><span id="reqInfo">*</span> Password</label>
          <input type="password" name="password" class="form-control" ng-model="register.user.password" ng-minlength="7" id="password"
            required="" placeholder="Enter your password">
          <div ng-messages="registerForm.password.$error" style="color:maroon" role="alert">
            <div ng-message="minlength">You Password must be at least 7 symbols long</div>
          </div>
        </div>

        <!-- Register button -->
        <div class="form-group">
          <button class="btn btn-primary" type="submit" ng-disabled="!registerForm.name.$valid || !registerForm.age.$valid || !registerForm.email.$valid || !registerForm.username.$valid || !registerForm.password.$valid">Register</button>
        </div>
        <p>Fields with <span id="reqInfo">*</span> must be filled.</p>
  </form>
  </div>

重要的是要知道我已被明确告知要在ES6中编写它。 我有逻辑问题,所以看看我的代码,请为我填写,以便我可以使用它,最重要的是 - 学习它:S 非常感谢你这么多!

1 个答案:

答案 0 :(得分:0)

我已经为不同类型的验证(sync Async)实现了一个指令,它也支持警告。 你可以从

查看
`https://plnkr.co/2WQHOo`

如果这是您所需要的并需要更多信息,请告诉我,我会尽力回答。