0

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

Bhushan Gadekar
  • 13,485
  • 21
  • 82
  • 131

2 Answers2

3

Since you just have a regex you could just use the pattern validator

city: new FormControl('',  Validators.pattern('[A-Za-z]'))
Kld
  • 6,970
  • 3
  • 37
  • 50
1

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

Pablo Lozano
  • 10,122
  • 2
  • 38
  • 59