how to validate website address using angular 5

itmannz picture itmannz · Mar 4, 2019 · Viewed 7.1k times · Source

I would like to validate url in angular 5 not working.

<input type="url" name="url" id="url" ngModel pattern="https?://.+">
<div *ngIf="url.errors && (url.dirty || url.touched)" class="alert alert-danger">

  <div [hidden]="!url.errors.pattern">
  </div>
</div>

Answer

Bear Nithi picture Bear Nithi · Mar 4, 2019

To Validate the URL / Web address in a reactive form you can follow the below method, using Validators.pattern against the form control.

const urlRegex = '(https?://)?([\\da-z.-]+)\\.([a-z.]{2,6})[/\\w .-]*/?';

 this.hospitalForm = this.fb.group({
   Website: ['', Validators.pattern(urlRegex)],
 });

To validate the URL / Web Address in a template driven form, you should create a custom Validator directive as follows

@Directive({
  selector: '[appPattern]',
  providers: [{provide: NG_VALIDATORS, useExisting: PatternValidatorDirective, multi: true}]
})
export class PatternValidatorDirective implements Validator {
  @Input('appPattern') pattern: string;

  validate(control: AbstractControl): {[key: string]: any} | null {
    return this.pattern ? this.patternValidator(new RegExp(this.pattern, 'i'))(control)
                              : null;
  }

 patternValidator(nameRe: RegExp): ValidatorFn {
   return (control: AbstractControl): {[key: string]: any} | null => {
           const regextest = nameRe.test(control.value);
           return (!regextest) ? {'apppattern': {value: control.value}} : null;
   };
  }
}

In your input, you should use appUrl with the regex, :

<input  type="url" name="url" id="url" ngModel appPattern="(https?://)?([\\da-z.-]+)\\.([a-z.]{2,6})[/\\w .-]*/?">