简体   繁体   English

Angular 2自定义表单验证仅在用户清除文本框值后才起作用

[英]Angular 2 custom form validation working only after user clear the textbox value

I'm trying to validate my input box immediately after the input box gets blur. 输入框变得模糊后,我试图立即验证输入框。 But some how the validation message only appears when i write something in textbox and than delete it. 但是有些验证消息仅在我在文本框中写东西然后删除时才显示。

Here's my HTML template; 这是我的HTML模板;

 <input type="text" placeholder="First Name" class="form-control" name="firstName" id="firstName" [ngModel]="typeValidation.firstName" #firstName="ngModel" (blur)="firstNameBlur(firstName.value)" autofocus required> <small [hidden]="firstName.valid || (firstName.pristine && !f2.submitted)" class="text-danger"> First Name is required. </small> 

Here's my typescript; 这是我的打字稿;

firstNameBlur(value:string) {

    if (value == "" || value == undefined) {
        return false;
    }
    else {
        return true;
    }

}

Please help me out. 请帮帮我。 Thanks in advance! 提前致谢!

To make it working as you expected, you should use untouched instead of pristine , like this: 要使其按预期工作,应使用untouched而不是pristine ,如下所示:

<small [hidden]="firstName.valid || (firstName.untouched && !f2.submitted)"
       class="text-danger">
  First Name is required.
</small>

or using *ngIf (IMHO, it's really better): 或使用* ngIf (恕我直言,这确实更好):

<small *ngIf="firstName.invalid && (firstName.touched || f2.submitted)"
       class="text-danger">
  First Name is required.
</small>

WORKING DEMO 工作演示

Note that you don't need (blur) . 请注意,您不需要(blur)

I'm not sure why you are binding to the blur event? 我不确定为什么要绑定到模糊事件? The required attribute should cause Angular to automatically validate the required field when the user leaves the field. 当用户离开字段时,required属性应使Angular自动验证所需字段。

And what is that code doing? 那段代码在做什么? Since the firstNameBlur() is executed on an event ... returning false is setting preventDefault. 由于firstNameBlur()是在事件...上执行的,因此返回false将设置preventDefault。 (See this link: https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault ) Is that what is intended? (请参阅此链接: https : //developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault )这是什么意思?

Try removing the blur event and see if it works without it. 尝试删除模糊事件,看看它是否有效。 If so, then you don't need the firstNameBlur method. 如果是这样,则您不需要firstNameBlur方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM