Search code examples
angularinputangular2-formsunsafe

Create a secure form in Angular 2+


I would like to create a secure form in Angular2+, using sanitize or something like that, but I try it and sanitize does not work with forms.

I would like to detect script and something like that.

I tried this:

    let title = form.title;
    console.log("TITLE", title) // title that I enter in my input
    title = this._sanitizer.sanitize(SecurityContext.HTML, title);
    console.log("after title", title)

But it does not work like I would like, because if I enter words with accents (áéíóú) or ¿?, it returns this:

  • Enter: áéíóú ¿hola?
  • Return: &#225 ;&#233 ;&#237 ;&#243 ;ú &#191 ;hola?

I would like to get the same that my enter data, but if I enter an script I can detect it to not save or not execute in my input.


Solution

  • There are some ways you can follow to achieve what you are trying to do. The sanitize doesn't filter your input data because this is not it's use.

    1) You can create a PIPE, that simply allow the user to type in the input text, for example, a certain chars. In case just check if the ascii key of what you've typed is in a certain range (for example 48-122 includes all numbers an letters A-a to Z-z).

    2) Use the same logic as point 1, but instead of creating a PIPE, you just create a function that return the string "sanitized" as you wish or that show a message if there are some wrong chars.

    3) This point may be off-topic. But if you have to send data to a web-server, just be sure to remove certains chars (like ',",!,=, IE: Injection) and the use the back-end language's function to properly "sanitize" the text.

    Anyway there is nothing by default that allow you to type only certain chars, or things like that. You have to code a bit. You didn't write what you are really trying to do,, but I suggest you to have a look at the angular's default PIPE, that are very useful to do a various kind of actions.