代码之家  ›  专栏  ›  技术社区  ›  dEs12ZER

如何在angular5和spring boot中使用自定义验证器

  •  0
  • dEs12ZER  · 技术社区  · 7 年前

    我在前端使用一个简单的angular5应用程序,在后端使用httpclient和spring boot,我正在创建一个简单的组件来添加一个新的客户端,其中包含字段username。

    我正在尝试使用custum验证器,以便检查用户名是否唯一或已被使用,但我有很多错误。 这是有角的一面

    新建-client.component.html

    <div >
      <div class="col-sm-10">
        <div class="card">
          <div class="card-header">
            <strong>add a new client</strong>
          </div>
    
          <form [formGroup]="form" (ngSubmit)="SaveClient()">
    
          <div class="card-body">
    
            <div class="form-group">
              <label for="vat">Email </label>
              <input type="text" class="form-control" id="vat"   formControlName="username" />
              <div class="error" *ngIf="form.controls['username'].invalid && form.controls['username'].errors.required && (form.controls['username'].dirty || form.controls['username'].touched)">Please enter an email</div>
              <div class="error" *ngIf="form.controls['username'].invalid && form.controls['username'].errors.email && (form.controls['username'].dirty || form.controls['username'].touched)">Please enter a valid email</div>
              <div class="error" *ngIf="form.controls['username'].invalid && form.controls['username'].errors.emailTaken">This email has been taken, please use another one.</div>
            </div>
            <div formGroupName = "passwordG">
    
              <div class="form-group">
                <label for="vat">Password</label>
                <input type="password" class="form-control" id="vat"    formControlName="password" />
              </div>
    
              <div class="form-group">
                <label for="vat">Confirmation Password</label>
                <input type="password" class="form-control" id="vat" formControlName="Confirmationpassword" />
              </div>
    
    
              <div *ngIf="(form.controls['passwordG'].invalid && form.controls['passwordG'].touched)" class="col-sm-3 text-danger">
    
                <ng-container *ngIf="form.controls['passwordG'].errors?.mismatch;
                    then first else second"> </ng-container>
    
                <ng-template #first>
                  Password do not match </ng-template>
    
                <ng-template #second>
                  Password needs to be more than 8 characters
                </ng-template>
              </div>
    
            </div>
          </div>
    
          <div class="card-footer">
            <button type="submit" class="btn btn-sm btn-primary" ><i class="fa fa-dot-circle-o"></i>Enregistrer</button>
          </div>
          </form>
        </div>
      </div><!--/.col-->
    </div>
    

    新建-client.component.ts

    function passwordMatch(control: AbstractControl):{[key: string]: boolean}{
    
      const password = control.get('password');
      const Confirmationpassword = control.get('Confirmationpassword');
    
      if( !password || !Confirmationpassword) {
        return null; }
    
      if(password.value === Confirmationpassword.value){
        return null;
      }
    
      return {
        mismatch:true
      }
    
    }
    
    
    @Component({
      selector: 'app-new-clients',
      templateUrl: './new-clients.component.html',
      styleUrls: ['./new-clients.component.scss']
    })
    export class NewClientsComponent implements OnInit {
    
      client:Clients = new Clients();
      form: FormGroup;
    
      constructor(private clientService:ClientService,
                  private formBuilder: FormBuilder,
                  public router:Router,
                  public activatedRoute:ActivatedRoute) { }
    
      ngOnInit() {
    
        this.form = this.formBuilder.group({
    
          username: ['', Validators.required , Validators.email  , this.validateEmailNotTaken.bind(this)],
          passwordG: this.formBuilder.group({
            password: ['',[Validators.required,Validators.minLength(9)]],
            Confirmationpassword : ['',[Validators.required,Validators.minLength(9)]]
    
          }, {validator: passwordMatch})
    
        });
      }
    
      SaveClient(){
    
        this.client.setUsername(this.form.value.username);
        this.client.setPassword(this.form.value.passwordG.password);
    
        this.clientService.saveClient(this.client)
          .subscribe((data:Clients)=>{
            swal("operation réussi !", "great !", "success");
            this.router.navigate([ '../list' ], { relativeTo: this.activatedRoute });
          },err=>{
            console.log(err);
          })
    
      }
    
      validateEmailNotTaken(control: AbstractControl) {
        return this.clientService.checkEmailNotTaken(control.value).map(res => {
          return res ? null : { emailTaken: true };
        }); //somthing is wrong HERE ! 
      }
    
    
    }
    

    客户服务.ts

    @Injectable()
    export class ClientService {
    checkEmailNotTaken(email:string){
        if(this.authService.getToken()==null) {
          this.authService.loadToken();
        }
        return this.http.post(this.host+
          "/checkEmailUnique/",{email},{headers:new HttpHeaders({'Authorization':this.authService.getToken()})});
      }
    
    
    }
    

    在弹簧靴中:

     @RequestMapping(value="/checkEmailUnique",method=RequestMethod.POST)
        public EmailStatusCheckJson checkEmailUnique(@RequestBody final AppUser appUser){
    
            final EmailStatusCheckJson returnValue = new EmailStatusCheckJson();
    
                  System.out.println("username **"+appUser.getUsername());
             AppUser app = userRepo.findByUsername(appUser.getUsername());
    
    
             if(app!=null){
                 System.out.println("exists");
                 returnValue.setEmailIsAvailable(false);
             }
             else{
                 System.out.println("doesnt exist ");
                 returnValue.setEmailIsAvailable(true);
    
             }
    
             return returnValue;
        }
    

    这就是我得到的错误

    ERROR Error: Expected validator to return Promise or Observable.
        at toObservable (forms.js:749)
        at Array.map (<anonymous>)
        at FormControl.eval [as asyncValidator] (forms.js:729)
        at FormControl.AbstractControl._runAsyncValidator (forms.js:3447)
        at FormControl.AbstractControl.updateValueAndValidity (forms.js:3390)
        at FormControl.setValue (forms.js:3973)
    

    有什么想法吗?我是新来的角度。

    2 回复  |  直到 7 年前
        1
  •  1
  •   JB Nizet    7 年前

    控件的表达式是

    • 控件的值,然后
    • 验证器或验证器数组,然后
    • 异步验证器或异步验证器数组

    ['', [Validators.required, Validators.email], this.validateEmailNotTaken.bind(this)]
    

    自从 validateEmailNotTaken 是异步验证程序。

        2
  •  1
  •   Antoniossss    7 年前

    你的括号不见了

    username: ['', Validators.required , Validators.email  , this.validateEmailNotTaken.bind(this)]
    

    应该是

    username: ['', [Validators.required , Validators.email  , this.validateEmailNotTaken.bind(this)]]