Pen Settings

HTML

CSS

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URLs added here will be added as <link>s in order, and before the CSS in the editor. You can use the CSS from another Pen by using its URL and the proper URL extension.

+ add another resource

JavaScript

Babel includes JSX processing.

Add External Scripts/Pens

Any URL's added here will be added as <script>s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.

+ add another resource

Packages

Add Packages

Search for and use JavaScript packages from npm here. By selecting a package, an import statement will be added to the top of the JavaScript editor for this package.

Behavior

Auto Save

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

Format on Save

If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.

Editor Settings

Code Indentation

Want to change your Syntax Highlighting theme, Fonts and more?

Visit your global Editor Settings.

HTML

              
                <body>
    <div id="root"></div>
</body>
              
            
!

CSS

              
                @import url('https://fonts.googleapis.com/css2?family=Dongle&family=Roboto:wght@400;900&display=swap');

:root {
	--black: #000000;
	--white: #ffffff;
	--background-color: #303030;
	--text-color: #ffffff;
}

* {
	padding: 0;
	margin: 0;
}

*,
*::before,
*::after {
	box-sizing: border-box;
}

body {
	font-family: 'Roboto', sans-serif;
}

input:-webkit-autofill,
input:-webkit-autofill:focus {
	-webkit-box-shadow: 0 0 0 50px var(--background-color) inset; /* Change the color to your own background color */
	-webkit-text-fill-color: var(--text-color);
}
              
            
!

JS

              
                const { createTheme, ThemeProvider, CssBaseline, Container, Grid, Paper, Box, TextField, Typography, Button, MenuItem } = MaterialUI;

type InitType = {
    [key: string]: any
}

type FormProps = {
    title?:string
}

type FormValidationItemType = {
            regex: RegExp,
            errorMsg: string
}

type FormValidationType = {
    [key: string]: {
        value: string,
        label: string,
        required?: boolean,
        valid: boolean,
        validation: Array<FormValidationItemType>,
        select?: Array<string> 
    }
}

const NO_ERROR = ' '; // empty char in order to display helper text field permanently
const FIELD_REQUIRED = {regex: /\S/g, errorMsg: 'Mandatory Field'};
const TITLE = 'Please provide your contact details:';
const ALERT = 'Your input Data:\n\n';

const theme = createTheme({
	palette: {
		mode: 'dark',
    primary: {
      main: '#fb8c00',
    },
    secondary: {
      main: '#b2ff59',
    },
    background: {
      default: '#303030',
      paper: '#303030'
    }
	},
	typography: {
		fontFamily: ['Roboto', 'sans-serif'].join(','),
    fontSize: 16,
    h1: {
      fontSize: '4.4rem',
    },
    h2: {
      fontSize: '3.6rem',
    },
    button: {
      fontSize: '1.2rem',
    }
	},
});

const initValue: FormValidationType = {
    title: {
        value: '',
        label: 'Title',
        valid: true,
        required: false,
        validation: [],
        select: ['Ms.', 'Mrs.', 'Mr.'],
    },
    firstName: {
        value: '',
        label: 'First Name',
        valid: true,
        required: true,
        validation: [
            {regex: /[0-9a-zA-Z]{3,}/g,
            errorMsg: 'Less than 3 or invalid characters.'},
        ],
    },
    lastName: {
        value: '',
        label: 'Last Name',
        valid: true,
        required: false,
        validation: [
            {regex: /[0-9a-zA-Z]{3,}/g,
            errorMsg: 'Less than 3 or invalid characters.'},
        ],
    },
    age: {
        value: '',
        label: 'Your age',
        valid: true,
        required: true,
        validation: [
            {regex: /^[0-9]{1,3}$/g,
            errorMsg: 'You need to input a valid number.'},
        ],
    },
    email: {
        value: '',
        label: 'Email',
        valid: true,
        required: false,
        validation: [
            {regex: /^[^\s@]+@[^\s@]+\.[^\s@]+$/g,
            errorMsg: 'Invalid email address.'},
        ],
    },
}

const useFormValidation = (props: FormValidationType) => {
    const {initValue, initValid, initHelperText} = getInitValues();
    const [value, setValue] = React.useState(initValue);
    const [isValid, setIsValid] = React.useState(initValid);
    const [helperText, setHelperText] = React.useState(initHelperText);

    function getInitValues(){
        let initValue: InitType = {};
        let initValid: InitType = {};
        let initHelperText: InitType = {};
        for (const [key, value] of Object.entries(props)) {
            initValue[key] = value.value;
            initValid[key] = value.valid;
            initHelperText[key] = NO_ERROR;
        }
        return {initValue, initValid, initHelperText};
    }

    let obj: InitType = {};

    for (const [key, val] of Object.entries(props)) {
        obj[key] = {
            value: value[key],
            isValid: isValid[key],
            required: val.required,
            bind: {
                value: value![key],
                onChange: (event: React.ChangeEvent<HTMLInputElement>) => {
                    setValue(prev => {
                        return {...prev, [key]: event.target.value};
                    });
                    const required = event.target.required;
                    let validationArr = required ? [FIELD_REQUIRED]: [];
                    validationArr = validationArr.concat(val.validation);
                    let errArr = validationArr.map(v => {
                        return event.target.value.search(v.regex);
                    });
                    let validationState = errArr.filter(i => i < 0).length === 0 ? true : false;
                    let index = errArr.findIndex(e => e === -1 );
                    let errorMsg = validationState ? NO_ERROR : validationArr[index].errorMsg;
                    setHelperText(prev => {
                        return {...prev, [key]: errorMsg};
                    });
                    setIsValid(prev => {
                        return {...prev, [key]: validationState};
                    });
                },
                helperText: isValid[key] ? NO_ERROR : helperText![key],
                error: !isValid[key],
            },
        }
    }
    obj.resetValue = () => {
        const {initValue, initValid, initHelperText} = getInitValues();
        setValue(initValue);
        setIsValid(initValid);
        setHelperText(initHelperText);
    }
    return obj;
}

const Form = (props: FormProps) => {

    const {title} = props;
    const obj  = useFormValidation(initValue);
    let valid =  Object.keys(initValue).map(item=>{
        let isValid = obj[item].isValid;
        let isNotRequired = obj[item].required ? false : true;
        let isRequiredAndNotEmpty = isNotRequired ? true: obj[item].value.length > 0;
        return isValid && isRequiredAndNotEmpty ;
    }).filter(x=>x).length === Object.keys(initValue).length;
        
    function sumbmit(){
        let str = ALERT;
        str += Object.keys(obj).map(item=>obj[item].value).join('\n');
        alert(str);
    }
    function reset(){
        obj.resetValue();
    }
   
  return <Box sx={{
      margin: 0,
      padding: 2,
      '& .MuiInput-root': {
        transition: theme=> theme.transitions.create(['background-color'], {
                duration: theme.transitions.duration.standard,
                easing: theme.transitions.easing.easeInOut,
        }),
        '&.Mui-focused' : {
          backgroundColor: 'background.default',
        }
      },
  }}>
      {title && (<Box><Typography variant="h3" sx={{fontWeight: 800, fontSize: '1.5rem', lineHeight: 1.1, mb: 2}}>{title}</Typography></Box>)}
      <Box>
          {
              Object.keys(initValue).map((item, index)=>{
                const itemObj = initValue[item];
                return (
                    <TextField variant="standard" size="medium" key={index} fullWidth id={item} {...obj[item]?.bind} label={itemObj.label} autoComplete="off" select={itemObj.select && itemObj.select.length > 0}>
                        {
                            itemObj.select && (
                                itemObj.select.map((sel, selIndex)=> {
                                    return (<MenuItem key={selIndex} value={ sel }>{ sel }</MenuItem>)
                                })
                            )
                        }
                    </TextField>)
              })
          }          
      </Box>
      <Box display="flex" justifyContent="space-around" sx={{my: 2}}>
        <Button variant="contained" onClick={reset}>Reset</Button>
        <Button variant="contained" disabled={!valid} onClick={sumbmit}>Send</Button>
      </Box>
  </Box>;
};

function App() {

 return (
  <ThemeProvider theme={theme}>
    <CssBaseline>
        <Container maxWidth="md" >
        <Grid container spacing={1} justifyContent="center" alignItems="center" sx={{minHeight: '100vh'}}>
          <Grid item></Grid>
          <Grid item xs={10} sm={8} md={6}>
            <Paper elevation={12} >
              <Form title={ TITLE } />
            </Paper>
          </Grid>
          <Grid item></Grid>
        </Grid >
      </Container>
    </CssBaseline>
  </ThemeProvider>
  );
}

ReactDOM.render(
  <App />,
  document.getElementById('root')
);
              
            
!
999px

Console