4

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>

1 Answer 1

3

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 .-]*/?">
Sign up to request clarification or add additional context in comments.

6 Comments

thanks for reponse. I am using template driven approach. not sure what Website: ['', Validators.pattern(urlRegex)], code is doing
Hi ,I have done below <label for="url" class="control-label">URL</label> <input (blur)="update(false)" required pattern="^(https?:\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?$" id="url" type="text" class="form-control" name="url" [(ngModel)]="urls" #url="ngModel"> <span class="help-block" *ngIf="url.errors?.required && url.touched"> URL is required </span> <span class="help-block" *ngIf="url.errors?.pattern && url.touched"> URL is Invalid </span> One issue is onblur get called when url.errors how to check on .ts file
what you mean by that issue? can you explain it a bit
I have tried you solution but patternValidator in not define please help
have you added it in your module declarations?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.