简体   繁体   中英

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

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

  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.

So, a better approach is to remove the inputs form and append to the DOM any content tag ( <span> , <p> , ...).

example:

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

You can do this with (ngModelChange) event:

HTML Code:

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

Add one property:

isInputValid: boolean = false;

isValid() as:

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]="!questionsForm.valid || isInputValid === false"

Working Stackblitz Example

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:

 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:

 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:

 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.

In your ts file you create custom validator function as follows:

  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. 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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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