Input validation with pattern Angular 2

前端 未结 2 1914
Happy的楠姐
Happy的楠姐 2021-02-15 14:07

I\'m currently writing a simple form in ionic 2 (Angular 2). I was wondering how I\'d add a simple regular expression pattern to the validation:

I basically have this:

2条回答
  •  無奈伤痛
    2021-02-15 14:14

    I put more details (Angular 2.0.8 - 3 March 2016): https://github.com/angular/angular/commit/38cb526

    Example from repo:

    
    

    I tested it, and it worked :) - here is my code:

    ...

    UPDATE September 2017

    I just wanna to say that currently when I have more experience, I usally use following 'cheap' approach to data validation:

    Validation is ONLY on server side (not in angular at all!) and if something is wrong then server (Restful API) return some error code e.g HTTP 400 and following json object in response body (which in angular I put to err variable ):

    this.err = { 
        "capacity" : "too_small"
        "filed_name" : "error_name", 
        "field2_name" : "other_error_name",
        ... 
    }
    

    (if server return validation error in different format then you can usually easily map it to above structure)

    In html template i use separate tag (div/span/small etc.)

    
    {{ translate(err.capacity) }}
    

    As you see, when there is some error in 'capacity' then tag with error translation (to user language) will be visible. This approach have following advantages:

    • it is very simple
    • in angular we not double validation code which is (and must be) in server (in case of regexp validation this can either prevent or complicate ReDoS attacks)
    • we have full control on way the error will be shown to user (here as egzample in tag)
    • because in server response we return error_name (instead of direct error message), we can easily change error message (or translate it) by modify only frontend-angular code (or files with translations). So in that case we not need to touch backend/server code.

    Of course sometimes (if this is needed - eg. retypePassword field which is never send to server) I make exceptions of above approach and make some validation in angular (but use similar "this.err" mechanism to show errors (so I not use pattern attribute directly in input tag but rather I make regexp validation in some component method after user raise proper event like input-change or save) .

提交回复
热议问题