Angular 5反应形式自定义验证器和必需验证器:必需验证器与自定义验证器一起使用时始终返回True

时间:2018-10-02 00:11:34

标签: angular angular-reactive-forms customvalidator

我试图将自定义验证器与所需的验证器以反应形式一起使用。自定义验证器的逻辑正常工作,并正确显示其错误消息。但是,在遍历代码时,所需的验证器始终返回true。结果,表单控件无效,并且即使表单中存在有效的用户输入,前端的控件仍保持红色。

我尝试从窗体控件中删除自定义验证器,并且所需的验证器行为正常。不确定为什么与自定义验证器一起使用时,所需的错误始终为true。

Component.ts

public Camera cameraSelf;
private Transform cameraTransform;
private Vector2 cameraRotation;

void FixedUpdate() {
  //  Camera.transform to be the same as camera targets body
  cameraSelf.transform.position = targetToLookAt.GetChild(0).GetChild(0).position;
  cameraSelf.transform.rotation = targetToLookAt.GetChild(0).GetChild(0).rotation;

  //    Moving camera with Mouse
  float pointer_x = Input.GetAxis("Mouse X");
  float pointer_y = Input.GetAxis("Mouse Y");
  //  Using Touch
  pointer_x = Input.touches[0].deltaPosition.x;
  pointer_y = Input.touches[0].deltaPosition.y;

  //  Mouse Movement
  cameraRotation.x += pointer_x * moveSensitivity * Time.deltaTime;
  cameraRotation.y -= pointer_y * moveSensitivity * Time.deltaTime;

  //  Set Rotation of Object
  targetToLookAt.position = cameraRotation;
}

Component.html

public AbsenceTypeName = new FormControl("", [Validators.required, 
     this.ValidateAbsenceTypeName.bind(this)]);

ValidateUserName(control: AbstractControl): any {

     const userName = control.value;

     const existingUserName = this.users.find(
       user =>
         user.userName.toUpperCase() ===
         userName.toUpperCase()) ? true : null;

     return { existingUserName: existingUserName };
}

1 个答案:

答案 0 :(得分:0)

custom validator可以返回2个值-如果您的验证没有失败:NULL如果验证失败:{object: "value"}

因此请根据以下内容更改代码:

ValidateUserName(control: AbstractControl): any {

     const userName = control.value;

     const existingUserName = this.users.find(
       user =>
         user.userName.toUpperCase() ===
         userName.toUpperCase()) ? true : null;

     return existingUserName? {existingUserName:"true"} : null;
}
相关问题