Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

added input validation to input component #7

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions dompurify.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
declare module 'dompurify' {
const DOMPurify: {
sanitize(input: string, config?: any): string;
// Add more typings for other functions if needed
};
export = DOMPurify;
}
22 changes: 19 additions & 3 deletions src/components/atoms/input-component/input-component.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { Component, Host, h, Prop } from "@stencil/core";
import cn from "classnames";
import DOMPurify from 'dompurify'; // will help validate input

@Component({
tag: "input-component",
Expand All @@ -22,7 +23,22 @@ export class InputComponent {
/** If true, the field is required */
@Prop() required = false;

private sanitizeInput( input: string ): string { // cleans dirty/potentially dangerous HTML
return DOMPurify.sanitize(input);
}

private validateInput( input: string): boolean { // validation function
if ( input.length <= 0 ) // input cannot be empty
return false;
// ! Insert other necessary validation here ! //
return true; // validation complete
}

render() {

const sanitizedLabel = this.sanitizeInput( this.label );
const checkInput = this.validateInput( sanitizedLabel ); // uses sanitized label

return (
<Host>
<div class="flex flex-col items-start gap-y-2">
Expand All @@ -32,10 +48,10 @@ export class InputComponent {
this.required,
})}
>
{this.label}
{ checkInput ? sanitizedLabel : 'Invalid Input'}
</label>

{this.helpText && <span>{this.helpText}</span>}
{this.helpText && <span>{this.sanitizeInput( this.helpText )}</span>}

<input
class={cn(
Expand All @@ -53,7 +69,7 @@ export class InputComponent {
placeholder={this.placeholder}
disabled={this.disabled}
// added interactive label
aria-label={this.label}
aria-label={ checkInput ? sanitizedLabel : 'Invalid Input'}
/>
</div>
</Host>
Expand Down
3 changes: 2 additions & 1 deletion tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,8 @@
"noUnusedLocals": true,
"noUnusedParameters": true,
"jsx": "react",
"jsxFactory": "h"
"jsxFactory": "h",
"typeRoots": ["./node_modules/@types", "macbis-design.github.io/dompurify.d.ts", ]
},
"include": ["src"],
"exclude": ["node_modules"]
Expand Down