Validation based on user selection in large form

form validation
validation in javascript for registration form
html form validation example
html5 form validation javascript
form validation using javascript code
jquery form validation
javascript form validation with error message
client side validation example

I have a user form in which i have multiple fields and based on the type of the user, i have used angular reactive forms and want to validate my fields

Here is my component ts code:

export class AppComponent implements OnInit {

userformGroup: FormGroup;
        Types = [ "user","admin", "guest"];
type: string;

constructor(
    private formBuilder: FormBuilder){}

ngOnInit() {
 this.userformGroup = this.formBuilder.group({
      type: ['user'],
       userName : [''],
      firstName :[''],
      lastName :[''],
        email :[''],
        contactNumber :[''],
        licenseNo :[''],
        age:[''],
        birthDate :[''],
        city:[''],
        country:[''],
        zipCode :[''],
        countryCode:['']
        });
  }

    updateValidators() {
    if (this.type === 'user') {
      this.userformGroup.get('userName').setValidators([Validators.required]);
      this.userformGroup.get('firstName').setValidators([Validators.required]);
      this.userformGroup.get('lastName').setValidators([Validators.required]);
      this.userformGroup.get('email').setValidators([Validators.required]);
      this.userformGroup.get('contactNumber').setValidators([Validators.required]);
       this.userformGroup.get('licenseNo').setValidators([Validators.required]);
         this.userformGroup.get('age').setValidators([Validators.pattern('/^-?(0|[1-9]\d*)?$/')]);
       this.userformGroup.get('birthDate').setValidators([Validators.required]);
       this.userformGroup.get('city').setValidators([Validators.required]);
        this.userformGroup.get('country').setValidators([Validators.required]);
       this.userformGroup.get('zipCode').setValidators([Validators.pattern('/^-?(0|[1-9]\d*)?$/')]);
     this.userformGroup.get('countryCode').setValidators([Validators.minLength(3)]);
    }
      else if(this.type === 'admin')
    {
      this.userformGroup.get('userName').setValidators([Validators.required]);
      this.userformGroup.get('firstName').setValidators([Validators.required]);
      this.userformGroup.get('lastName').setValidators([Validators.required]);
      this.userformGroup.get('email').setValidators([Validators.required]);
      this.userformGroup.get('contactNumber').setValidators([]);
       this.userformGroup.get('licenseNo').setValidators([Validators.required]);
         this.userformGroup.get('age').setValidators([Validators.pattern('/^-?(0|[1-9]\d*)?$/')]);
       this.userformGroup.get('birthDate').setValidators([]);
       this.userformGroup.get('city').setValidators([Validators.required]);
        this.userformGroup.get('country').setValidators([]);
       this.userformGroup.get('zipCode').setValidators([Validators.pattern('/^-?(0|[1-9]\d*)?$/')]);
     this.userformGroup.get('countryCode').setValidators([Validators.minLength(3)]);    
    }
      else if(this.type === 'guest')
    {
      this.userformGroup.get('userName').setValidators([]);
      this.userformGroup.get('firstName').setValidators([]);
      this.userformGroup.get('lastName').setValidators([Validators.required]);
      this.userformGroup.get('email').setValidators([]);
      this.userformGroup.get('contactNumber').setValidators([]);
       this.userformGroup.get('licenseNo').setValidators([Validators.required]);
         this.userformGroup.get('age').setValidators([]);
       this.userformGroup.get('birthDate').setValidators([]);
       this.userformGroup.get('city').setValidators([Validators.required]);
        this.userformGroup.get('country').setValidators([]);
       this.userformGroup.get('zipCode').setValidators([Validators.pattern('/^-?(0|[1-9]\d*)?$/')]);
     this.userformGroup.get('countryCode').setValidators([Validators.minLength(3)]);    
    }
     this.userformGroup.get('userName').updateValueAndValidity();
    this.userformGroup.get('firstName').updateValueAndValidity();
    this.userformGroup.get('lastName').updateValueAndValidity();
    this.userformGroup.get('email').updateValueAndValidity();
    this.userformGroup.get('contactNumber').updateValueAndValidity();
    this.userformGroup.get('licenseNo').updateValueAndValidity();
    this.userformGroup.get('age').updateValueAndValidity();
    this.userformGroup.get('birthDate').updateValueAndValidity();
    this.userformGroup.get('city').updateValueAndValidity();
    this.userformGroup.get('country').updateValueAndValidity();
    this.userformGroup.get('zipCode').updateValueAndValidity();
    this.userformGroup.get('countryCode').updateValueAndValidity();
    }
    onChange(event: any) {
    this.type = event.target.value;
    this.updateValidators();
  }
}

This code is working fine, but I'm looking for a optimized way of validating it, how can i do that so that i dont have to repeatedly apply validation on the same fields?

Stackblitz

Instead of making custom validation functions or writing too much of code in the component, You can use validation based on user's selection by using conditional expression, Here i have used validation from @rxweb validators(RxwebValidators).

The optimal code is :

export class UserInfoAddComponent implements OnInit {

    userInfoFormGroup: FormGroup
        Types = [ "user","admin", "guest"];
    constructor(
        private formBuilder: RxFormBuilder
    ) { }

   ngOnInit(){
    this.userInfoFormGroup = this.formBuilder.group({
      type:[''],
      userName :['',RxwebValidators.required({conditionalExpression:(x) => x.type == 'user' })],
      firstName :['',RxwebValidators.required({conditionalExpression:(x) => x.type == 'user' })],
      lastName :['',RxwebValidators.required({conditionalExpression:(x) => x.type == 'user' })],
      email :['',RxwebValidators.required({conditionalExpression:(x) => x.type == 'user' })],     
        contactNumber :['',RxwebValidators.required({conditionalExpression:(x) => x.type == 'user' })],   
      licenseNo :['',RxwebValidators.required({conditionalExpression:(x) => x.type == 'user' })],  
     age:['', RxwebValidators.pattern({expression:{'onlyDigit': /^[0-9]*$/}  ,conditionalExpression:(x) => x.type == 'user' })], 
     birthDate:['',RxwebValidators.required({conditionalExpression:(x) => x.type == 'user' })],
      city:['',RxwebValidators.required({conditionalExpression:(x) => x.type == 'user' })],
      country:['',RxwebValidators.required({conditionalExpression:(x) => x.type == 'user' })],
      zipCode:['',RxwebValidators.pattern({expression:{'zipCode': /^-?(0|[1-9]\d*)?$/}  ,conditionalExpression:(x) => x.type == 'user' })], 
       countryCode:['',RxwebValidators.minLength({value:3,conditionalExpression:(x) => x.type == 'user' })], 


    });


    }
}

Stackblitz working example

Web Form Validation: Best Practices and Tutorials — Smashing , The goal of web form validation is to ensure that the user provided necessary and Surprisingly, large websites such as Facebook, LinkedIn,� The constraint validation API gives you a powerful tool to handle form validation, letting you have enormous control over the user interface above and beyond what you can do with HTML and CSS alone. Note : For further information, see our Constraint validation guide , and the Constraint Validation API reference.

You could write a custom validator function that applies different validation based on the current user type:

requiredForTypes(...types: string[]): ValidatorFn {
  return (control: AbstractControl) => {
    if (types.indexOf(this.type) > -1) {
      return Validators.required(control);
    }
    return null;
  }
}

Then update your Form Controls to use the custom validator:

this.userformGroup = this.formBuilder.group({
  type: [this.type, Validators.required],
  userName: new FormControl('', this.requiredForTypes('user', 'admin')),
  firstName: new FormControl('', this.requiredForTypes('user', 'admin')),
  lastName: new FormControl('', Validators.required),
  email: new FormControl('', this.requiredForTypes('user', 'admin')),
  contactNumber: new FormControl('', this.requiredForTypes('user')),
  licenseNo: new FormControl('', Validators.required),
  age: new FormControl('', Validators.pattern('/^-?(0|[1-9]\d*)?$/')),
  birthDate: new FormControl('', this.requiredForTypes('user')),
  city: new FormControl('', Validators.required),
  country: new FormControl('', this.requiredForTypes('user')),
  zipCode: new FormControl('', Validators.pattern('/^-?(0|[1-9]\d*)?$/')),
  countryCode: new FormControl('', Validators.minLength(3)),
});

Finally, trigger validation whenever the user type changes:

this.userformGroup.controls.type.valueChanges.subscribe(type => {
  this.type = type;

  Object.keys(this.userformGroup.controls).forEach(key => {
    if (key !== 'type') {
      this.userformGroup.controls[key].updateValueAndValidity();
    }
  })
});

StackBlitz Example.

Validation based on user selection in large form - angular - html, I have a user form in which i have multiple fields and based on the type of the user, i have used angular reactive forms and want to validate my fields Here is my� You can improve overall data quality by validating user input for accuracy and completeness. This page shows how to validate user input from the UI and display useful validation messages, in both reactive and template-driven forms. Prerequisites. Before reading about form validation, you should have a basic understanding of the following.

You can reorganize your validation conditions.

  1. Apply validation directly to declaration that are common to all 3 types.

    this.userformGroup = this.formBuilder.group({
        type: ['user'],
        userName: [''],
        firstName: [''],
        lastName: ['', [Validators.required]],
        email: [''],
        contactNumber: [''],
        licenseNo: ['', [Validators.required]],
        age: [''],
        birthDate: [''],
        city: ['', [Validators.required]],
        country: [''],
        zipCode: ['', [Validators.pattern('/^-?(0|[1-9]\d*)?$/')]],
        countryCode: ['', [Validators.required, Validators.minLength(3)]]
    });
    
  2. Reorganize if else block in updateValidators function

    if (this.type === 'user' || this.type === 'admin') {
        this.userformGroup.get('userName').setValidators([Validators.required]);
        this.userformGroup.get('firstName').setValidators([Validators.required]);
        this.userformGroup.get('email').setValidators([Validators.required]);
        this.userformGroup.get('age').setValidators([Validators.pattern('/^-?(0|[1-9]\d*)?$/')]);
    } else {
        this.userformGroup.get('userName').setValidators([]);
        this.userformGroup.get('firstName').setValidators([]);
        this.userformGroup.get('email').setValidators([]);
        this.userformGroup.get('age').setValidators([]);
    }
    
    if (this.type === 'user') {
        this.userformGroup.get('contactNumber').setValidators([Validators.required]);
        this.userformGroup.get('birthDate').setValidators([Validators.required]);
        this.userformGroup.get('country').setValidators([Validators.required]);
    }
    else {
        this.userformGroup.get('contactNumber').setValidators([]);
        this.userformGroup.get('birthDate').setValidators([]);
        this.userformGroup.get('country').setValidators([]);
    }
    
  3. You don't need to call updateValueAndValidity on the control's of which validation never changes.

I noticed some other problems with your code.

  1. onChange function is never getting called from html.
  2. updateValidators function not getting called when form initialized. it is required in this case as you are assigning 'user' value to type control. Add these 2 lines after form initialization.

    this.type = 'user';
    this.updateValidators();
    
  3. There is a typo in html line 12. should be

    formControlName="userName"
    

Client-side form validation, Always remember to help your users correct the data they provide. Built-in form validation has better performance than JavaScript, but it is not as attribute suffices in making a selection a requirement --> <input type="radio" required Point out exactly where the error occurs, especially on large forms. We can validate a listbox inside a form by using JavaScript. We will allow the form to be submitted only if the user select one option from the listbox. Our JavaScript function will display one alert window asking user to select one option before submitting the form. demo of listbox validation → We will display a form with a listbox inside it.

Validating Form Data with a Flow, Validation Forms evaluate input Data, and output the data or information on Component � Uploading and Downloading Large Files with File References based on the result of the Flow and the user action on the Form. In a Designer Folder, select the CREATE FLOW button from the bottom Action Bar. E.g. In a "Project Cost" list, user must fill "Budget Amount" field value if "Budget Approved" field's value is set to "True". Solution: Here is how to implement a required field validation based on other column's value in SharePoint 2013. Head on to List Settings; Click on "Validation settings" under "General Settings"

11 Awesome Examples of Data Validation, It often goes unnoticed as Excel users are eager to learn the highs of PivotTables , charts and formulas. First select the range of cells you want to apply the validation to. You can create Data Validation rules that are based on the value Alan is the founder of Computergaga and has a large YouTube� Select the cell where you want to apply this condition. In the above example, it is cell B5. Go to Data –> Data Tools –> Data Validation In the data validation dialogue box, select the settings tab and make the following changes: Allow: Date; Data: Between; Start Date: Enter the start date here (any date that is before this date will not be

Form Validation with JavaScript, Validating drop-down lists. Next the “Age” drop-down list is checked to see if the user has selected an option. In the form, we named the� By seeing a progress bar, users are more motivated to complete the form. This is, again, based on numerous proven cognitive biases such as the endowed progress effect. 2. Remove all non-essential fields. Expedia lost $12 million per year by asking one additional question (company name) in their booking form.

Comments
  • @DeborahK in the link you provided it says: onlySelf: When true, only update this control. When false or not supplied, update all direct ancestors. Default is false. It does not update validation status on children.