Created
January 27, 2018 16:21
-
-
Save guillefd/dc50900569f289b7533ed7c752fc2174 to your computer and use it in GitHub Desktop.
Angular Form Validator Pattern: only letters and numbers
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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ñÑáéíóúÁÉÍÓÚ ]+$')] | |
], | |
}); | |
} | |
} |
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...
What does this "9ñÑáéíóúÁÉÍÓÚ" part of the validator do?
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
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