Home > Software design >  Apply ngIf validity on submit
Apply ngIf validity on submit

Time:08-30

I validate a few fields in a form in my Angular 10 project like this:

    <div >
      <div >
        <h5>1. Requestors Name (Your name or JHED ID)</h5><p >*</p>
      </div>
      <input type="text"  id="requestorName" name="requestorName" required minlength="2"
             [(ngModel)]="model.requestorName" #requestorName="ngModel"/>
      <div *ngIf="requestorName.invalid && (requestorName.dirty || requestorName.touched)"
           >
        <div *ngIf="requestorName.errors?.required">
          <p >Requester name is required.</p>
        </div>
        <div *ngIf="requestorName.errors?.minlength">
          <p >Requester name must be at least 2 characters long.</p>
        </div>
      </div>
    </div>

Which works fine. However, if the user never touches the fields that have validation like this but fill out the rest of the form then click Submit it will still be acceptable.

I also have written my own validation check on submit like this:

<div >
   <button  (click)="onSubmit()">Submit</button>
</div>
validateModel(accessRequest: AccessRequestModel) {
    const validityCheck = {
      isValid: true,
      reason: null
    };
    validityCheck.isValid = true;
    console.log(accessRequest);
    if (accessRequest) {
      if (!accessRequest.requestorName) {
        validityCheck.isValid = false;
        validityCheck.reason = 'Requester name is required.';
        return validityCheck;
      } else if (!accessRequest.lname) {
        validityCheck.isValid = false;
        validityCheck.reason = 'Last name is required.';
        return validityCheck;
      }
      else if (!accessRequest.fname) {
        validityCheck.isValid = false;
        validityCheck.reason = 'First name is required.';
        return validityCheck;
      }
      else if (!accessRequest.department) {
        validityCheck.isValid = false;
        validityCheck.reason = 'Department is required.';
        return validityCheck;
      }
      else if (!accessRequest.title) {
        validityCheck.isValid = false;
        validityCheck.reason = 'Job title is required.';
        return validityCheck;
      }
      else if (!accessRequest.managerName) {
        validityCheck.isValid = false;
        validityCheck.reason = 'Manager name is required.';
        return validityCheck;
      }
      else if (!accessRequest.startDate) {
        validityCheck.isValid = false;
        validityCheck.reason = 'Start date is required.';
        return validityCheck;
      }
      else if (!accessRequest.accessType) {
        validityCheck.isValid = false;
        validityCheck.reason = 'Access type is required.';
        return validityCheck;
      }
    }
    return validityCheck;
  }

Which also works.

But what I want is for the same error messages that apply if you do click on the boxes to apply if the validity check function returns false. How could I do that?

If the question wasn't clear or you need additional information please let me know.

CodePudding user response:

Seems like you are trying to recreate form validation. Look into reactive forms module in angular and do the following:

  • Import ReactiveFormsModule into the module where your component is defined

  • Dependency Inject it to your component's constructor like so:

    constructor(private formBuilder: FormBuilder) {}
    
  • Define the form creation logic in your OnInit method:

    ngOnInit() {
    
    this.myForm = this.formBuilder.group({
        option1: ['', Validators.Required],
        ...
      })
    }
    
  • Update your HTML to leverage this new form based on the documentation that angular provides. Thus your submit button can define a [disabled] attribute that sets a button as disabled if the form is not valid. The syntax in the form group of: [{initialValue}, {validator | array of validators}] is what controls the validity of the input.

Conversely, you can also iterate over each control in the form and manually set the error state for it by calling the setError method on the FormControl object if you still want to enable a user to click submit even on an invalid form input.

  • Related