简体   繁体   English

angular4-当输入为空或值小于1时禁用表格

[英]angular4 - disable form when input is empty or value less than 1

I'm validating forms in an angular project which is working as it should. 我正在验证一个按计划工作的有角项目中的表单。 But i'm trying to go a step further by disabling the form when a value in a particular textfield noWards is less than 1 但是我正在尝试通过在特定文本字段noWards值小于1时禁用表单来更进一步

Textbox 文本框

  <input autocomplete="off" class="input100" type="text"   formControlName="noWards" [(ngModel)]="noWards" >

Button 按键

    <button
    [disabled]="!questionsForm.valid || noWards.length < 3"
    [ngClass]="{'default':!questionsForm.valid}"
    (click)="goToNextStep()" class="contact100-form-btn">
      <span>
        Start
        <i class="fa fa-long-arrow-right m-l-7" aria-hidden="true"></i>
      </span>
    </button>

JS JS

  this.questionsForm = this.formBuilder.group({
            new: ['', Validators.required],
            noWards: ['', Validators.required],
            user: [''],
            pass: ['', Validators.required]
          });

Instead the form, you could disable the inputs form , actually this is not a good strategy, because a malicious user can overwrite such property from the DOM. 相反,您可以禁用输入表单 ,实际上这不是一个好策略,因为恶意用户可以从DOM覆盖此类属性。

So, a better approach is to remove the inputs form and append to the DOM any content tag ( <span> , <p> , ...). 因此,更好的方法是删除输入表单 ,并将任何内容标签<span><p> ,...)添加到DOM。

example: 例:

<input *ngIf="isEditable" type="text" ... [(ngModel)]="Name">
<span *ngIf="!isEditable"> {{Name}} </span>

You can do this with (ngModelChange) event: 您可以使用(ngModelChange)事件来执行此操作:

HTML Code: HTML代码:

<form [formGroup]="questionsForm">
    <input autocomplete="off" class="input100" type="text"   formControlName="noWards" [(ngModel)]="noWards" (ngModelChange)="isValid(noWards)" required>
<button
    [disabled]="!questionsForm.valid || isInputValid === false"
    (click)="goToNextStep()" class="contact100-form-btn">
    Test
    </button>
 </form>

In TS: 在TS中:

Add one property: 添加一个属性:

isInputValid: boolean = false;

isValid() as: isValid()为:

isValid(data) {
    var valid = /^([0-9]*[1-9][0-9]*)$/.test(data);
    if (valid) {
      this.isInputValid = true
    }
    else {
      this.isInputValid = false;
    }
  }

The [disabled] property condition: [disabled]属性条件:

[disabled]="!questionsForm.valid || isInputValid === false"

Working Stackblitz Example 工作Stackblitz示例

If you are talking about the string length of the field noYards , you can use the Validator Class that come from the Reactive Form Module via Validators.minLength() or Validators.maxLength() like this: 如果您在谈论字段noYardsstring length ,则可以通过Validators.minLength()Validators.maxLength()使用来自Reactive Form ModuleValidator类,如下所示:

 this.questionsForm = this.formBuilder.group({ new: ['', Validators.required], noWards: ['', Validators.minLength(1)], user: [''], pass: ['', Validators.required] }); 

But if you are talking about the type number value of your field, you can implement a Custom Validation function and pass it to your FormControl like this: 但是,如果您要谈论字段的类型number值,则可以实现“ Custom Validation function并将其传递给FormControl如下所示:

 import { AbstractControl } from '@angular/forms'; export function ValidateNoYards(control: AbstractControl) { if (control.value < 1) { return { validNoYards: false }; } return true; } 

And in your Component use it: 并在您的Component使用它:

 this.questionsForm = this.formBuilder.group({ new: ['', Validators.required], noWards: ['', ValidateNoYards], user: [''], pass: ['', Validators.required] }); 

This should work. 这应该工作。

As you are working with reactive forms, you should use custom validators to validate your field. 在使用反应式表单时,应使用自定义验证器来验证字段。

Also, you can use type="number" in your input field to make ensure only number in entered in that field. 另外,您可以在输入字段中使用type="number"来确保仅在该字段中输入数字。

In your ts file you create custom validator function as follows: 在ts文件中,创建自定义验证程序函数,如下所示:

  validatenoWards(control: FormControl) {
    if (control.value<1) {
      return { inValid: true };
    }
    return null;
  }

Custom validator should return null if control value is valid or else, it should return any object as in the function above. 如果控制值有效,则自定义验证器应返回null,否则应返回上述函数中的任何对象。 And then in the form group, use it as: 然后在表单组中,将其用作:

this.questionsForm = this.formBuilder.group({
            new: ['', Validators.required],
            noWards: ['', [this.validatenoWards,Validators.required]]],
            user: [''],
            pass: ['', Validators.required]
          });

And then to keep your button disabled while noWards is less than 1, simply user the disabled attribute of form valid condition as below: 然后在noWards小于1的情况下使按钮保持禁用noWards ,只需使用表单有效条件的disable属性,如下所示:

<button
    [disabled]="!questionsForm.valid"
    (click)="goToNextStep()" class="contact100-form-btn">
    Test
    </button>

You can perform any logic in the custom validator to check if the input field is valid. 您可以在定制验证器中执行任何逻辑,以检查输入字段是否有效。 You can also show custom messages based on the validity. 您还可以根据有效性显示自定义消息。 For more on custom validators, see : Creating a Custom Validator . 有关自定义验证器的更多信息,请参见: 创建自定义验证器

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

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