Skip to content

Instantly share code, notes, and snippets.

@guillefd
Created January 27, 2018 16:21
Show Gist options
  • Save guillefd/dc50900569f289b7533ed7c752fc2174 to your computer and use it in GitHub Desktop.
Save guillefd/dc50900569f289b7533ed7c752fc2174 to your computer and use it in GitHub Desktop.
Angular Form Validator Pattern: only letters and numbers
import { Component } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
@Component({
selector: 'form',
templateUrl: './form.component.html',
styleUrls: ['./form.component.scss']
})
export class Form {
form: FormGroup;
constructor(private fb: FormBuilder) {
this.form = this.fb.group({
title: ['', [Validators.pattern('^[A-Za-z0-9ñÑáéíóúÁÉÍÓÚ ]+$')]
],
});
}
}
@guillefd
Copy link
Author

guillefd commented Jan 8, 2021

hi!

  • import on your component
    import { FormBuilder, FormGroup, Validators } from '@angular/forms';

  • setup on the view
    <input type="text" formControlName="title">

  • set on your form builder element

this.form = this.fb.group({
            title: ['', [Validators.pattern('^[A-Za-z0-9ñÑáéíóúÁÉÍÓÚ ]+$')]
            ]

@aarekaarid
Copy link

I was struggling with adding 'Validator.required' to existing one, but solved it eventually:
this.form = this.fb.group({
title: ['', [Validators.pattern('^[A-Za-z0-9ñÑáéíóúÁÉÍÓÚ ]+$'),
Validators.required]
]

Thanks, it was a good example...

@alicelebidev
Copy link

What does this "9ñÑáéíóúÁÉÍÓÚ" part of the validator do?

@guillefd
Copy link
Author

It allows this special chars to be typed, required for spanish language.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment