1

In angular version: 2.1.1, I've create a form with form builder, one controller is for inputting coordinates (latlng) from google maps. I've defined the coordinates format with regex as:

  • (-?\d+(.\d+)?),\s*(-?\d+(.\d+)?)

Thus a valid string would be:

  • 2.3, 4.66

I've set my validator as:

this.addressForm = this.formBuilder.group({
  "geoLocationLatLng":[null, [
     Validators.required,
     Validators.maxLength(150), 
     Validators.pattern("(\-?\d+(\.\d+)?),\s*(\-?\d+(\.\d+)?)")]],
});

Question, why is pattern validation not working?

enter image description here enter image description here

Carlo Luther
  • 2,402
  • 7
  • 46
  • 75
  • 2
    Use `Validators.pattern("-?\\d+(\\.\\d+)?,\\s*-?\\d+(\\.\\d+)?")` – Wiktor Stribiżew Nov 10 '16 at 17:20
  • 1
    Also, why not use `Validators.pattern(/^-?\d+(\.\d+)?,\s*-?\d+(\.\d+)?$/)`? – Wiktor Stribiżew Nov 10 '16 at 17:27
  • @Wiktor Stribiżew OMG, I've spent more than 3 hours on this, I've also upgraded angular2 library... and it was all down to escape characters, shame on me. Btw thanks. The correct sequence is (\\-?\\d+(\\.\\d+)?),\\s*(\\-?\\d+(\\.\\d+)?) – Carlo Luther Nov 10 '16 at 17:27
  • You do not need to escape the hyphens. `"-?\\d+(\\.\\d+)?,\\s*-?\\d+(\\.\\d+)?"` should work, too. But doesn't `Validators.pattern(/^-?\d+(\.\d+)?,\s*-?\d+(\.\d+)?$/)` work? – Wiktor Stribiżew Nov 10 '16 at 17:27
  • @Wiktor Stribiżew Answer the question so that I can vote you. – Carlo Luther Nov 10 '16 at 17:29
  • Actually, I think your question is a duplicate of http://stackoverflow.com/questions/17863066/why-do-regex-constructors-need-to-be-double-escaped or http://stackoverflow.com/questions/3903488/javascript-backslash-in-variables-is-causing-an-error. Or better - http://stackoverflow.com/questions/2668544/javascript-a-backslash-as-part-of-the-string – Wiktor Stribiżew Nov 10 '16 at 17:30
  • nope (/^-?\d+(\.\d+)?,\s*-?\d+(\.\d+)?$/) does not work – Carlo Luther Nov 10 '16 at 17:30

0 Answers0