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

1
  • Can you please plunker/fiddle? Commented Aug 10, 2017 at 12:32

2 Answers 2

3

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

city: new FormControl('',  Validators.pattern('[A-Za-z]'))
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

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.