Angular5和spring-boot中的唯一字段验证

时间:2018-06-21 11:22:31

标签: java spring angular spring-boot angular5

我在前端使用一个简单的angular5应用程序,在后端使用spring-boot,我正在创建一个简单的组件来添加具有字段用户名的新客户端。

我正尝试使用custum验证程序,以便我可以检查用户名是否唯一或已使用,但我遇到了许多与自身代码相关的错误。

这是角边

new-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>

new-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 };
    });
  }


}


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({
      prenom: ['', Validators.required],
      nom: ['', Validators.required],
      tel: ['', Validators.required],
      cin: ['', Validators.required],
      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.client.setPrenom(this.form.value.prenom);
    this.client.setNom(this.form.value.nom);
    this.client.setTel(this.form.value.tel);
    this.client.setCin(this.form.value.cin);

    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 };
    });
  }


}

client.service.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 boolean checkEmailUnique(@RequestBody String username){

             System.out.println("username***************"+username);
         AppUser app = userRepo.findByUsername(username);
        System.out.println("************* pp"+app.getUsername()+"***************************");

         if(app!=null){
             System.out.println("already exists ! ***********************");
             return true;
         }
         else{
             System.out.println("noooo exists ! ***********************");
             return false  ;

         }
    }

}

我敢肯定,此代码本身无法实现。

这是我遇到的错误

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)

但是正如我说的那样,我在弹簧方面做错了,或者自定义验证器的编写方式不是安全的。

有什么想法吗?

0 个答案:

没有答案