Reputation: 13805
I am trying to create a custom validator in angular 4 project which will only allow characters other than numbers to be typed.
So Far I have tried multiple options but none seem to work.
I am doing something like this:
Component
ngOnInit() {
this.form = new FormGroup({
...
city: new FormControl('', validateCity)
});
}
Validator
import { FormControl } from '@angular/forms';
function validateCity(c: FormControl) {
let CITY_REGEXP = /^[a-z0-9!#$%&'*+\/=?^_`{|}~.-]/i;
return CITY_REGEXP.test(c.value) ? null : {
validateCity: {
valid: false
}
};
}
am I doing something wrong? thanks
Upvotes: 0
Views: 1364
Reputation: 10342
Your regular expression is not correct:
let CITY = /^[a-z0-9!#$%&'*+\/=?^_`{|}~.-]/i;
console.log(CITY.test('Hello9'))
You need a regex that matches only characters and spaces:
let re=/^[A-Za-z ]+$/
console.log (re.test('Barcelona')) //true
console.log(re.test('Los Angeles')) //true
console.log(re.test('Paris 9')) //false
But maybe you need to allow accents, umlauts ... so you can check this SO question
Upvotes: 1
Reputation: 7068
Since you just have a regex
you could just use the pattern
validator
city: new FormControl('', Validators.pattern('[A-Za-z]'))
Upvotes: 3