manni
manni

Reputation: 717

emberjs field validation regex

i have a custom emberjs field like this

App.NameTextField = App.FieldView.extend({
ValidationText: '',
IsValid: function(){
    var valText = this.get('ValidationText');
    return valText == '';
}.property(),
Regex: null,
DataView: Ember.TextField.extend({
    nameValue: function(){
        return App.FormContact.get('FirstName');
    }.property(),
    ValidationMessages: {Req: 'this is required. fill it in.', Invalid: 'invalid name', Valid: ''},
    valueBinding: 'nameValue',
    Regex: function(){
        return this.get('parentView').get('Regex');
    }.property(),
    IsRequired: function(){
        return this.get('parentView').get('IsRequired');
    }.property(),
    focusOut: function(){
        var reg = new RegExp(this.get('Regex'));
        var val = this.get('value');
        var validMsg = validateName(this.get('IsRequired'), val, reg);
        this.get('parentView').set('ValidationText', this.ValidationMessages[validMsg]);
    }
})

});

in the front end, i'm assigning the regex like this:

 <p>{{view Rewards.NameTextField size="50px" label="First Name" Regex="/^[A-Za-z-'.\s]+$/"}}</p>

it's a problem because when i do "this.get('Regex')" in DataView, it evaluates to

//^[A-Za-z-'.\s]+$//

causing my Regex to evaluate incorrectly. so how do i dynamically assign a Regex value to a view in the template?

thanks in advanced!

Upvotes: 1

Views: 2358

Answers (2)

manni
manni

Reputation: 717

I removed the slash in at the beginning and at the end so now it's just Regex="^[A-Za-z-'.\s]+$" and it's working! Having the slashes results in extra slashes when getting the regex value in the App js. the result is

<p>{{view Rewards.NameTextField size="50px" label="First Name" Regex="^[A-Za-z-'.\s]+$"}}    </p>

Upvotes: 0

Justin Morgan
Justin Morgan

Reputation: 30660

I was about to suggest removing the slashes, but you also have an unescaped hyphen inside your character class. This will fail to match a literal - character. You should change the regex to one of the following if you want the last hyphen to be treated literally:

  • ^[A-Za-z'.\s-]+$ - hyphen at the end
  • ^[-A-Za-z'.\s]+$ - hyphen at the beginning
  • ^[A-Za-z\-'.\s]+$ - escaped hyphen

I see this mistake on Stack Overflow quite a lot. Check out this article from regular-expressions.info for an explanation of how hyphens work inside character classes (see the "Metacharacters Inside Character Classes" section).

Upvotes: 2

Related Questions