Search code examples
reactjscode-injectionyum

How to prevent from injecting HTML and scripts in a TextField with React and Yum


I have this chunck of code meant to input a description:

 <Grid item xs={12}>
    <Typography align="left" variant="h6" gutterBottom>
        Description
    </Typography>
    {console.log(values)}
    <Field 
        name="description"
        multiline
        fullWidth
        rows={4}
        as={TextField}
        helperText={
        getIn(touched, "description")
            ? getIn(errors, "description")
            : ""
        }
        error={
        getIn(errors, "description") &&
        getIn(touched, "description")
        }
    />
</Grid>   

As I'm fairly new to React and the validation via Yum, I was wondering if there was a way to prevent the injection of HTML code or script on the front-end side.

Thanks for reading ! Have a nice day :)


Solution

  • Yes you could make a custom script to handle it but that would be too much work, you can make use of a package like DOMPurify to clean the user-generated content before it is sent to the backend/server

    Example

    let user-generated-content = "Dirty user-generated content"
    

    the above value can be cleaned of any script by doing the below

    let clean = DOMPurify.sanitize(user-generated-content);
    

    then you would pass clean where ever you would have passed user-generated-content

    you can check out their demo