Skip to content

Instantly share code, notes, and snippets.

@kellenff
Created December 14, 2020 02:37
Show Gist options
  • Save kellenff/8140ece0f4d9c31dc9556092315074cc to your computer and use it in GitHub Desktop.
Save kellenff/8140ece0f4d9c31dc9556092315074cc to your computer and use it in GitHub Desktop.
import React, { useState } from 'react';
import {
IsOptional,
MinLength,
registerDecorator,
validateSync,
ValidationArguments,
ValidationOptions,
} from 'class-validator';
import { plainToClass } from 'class-transformer';
function IsEmail(validationOptions?: ValidationOptions) {
return function (object: Object, propertyName: string) {
registerDecorator({
name: 'isEmail',
target: object.constructor,
propertyName,
constraints: [],
options: validationOptions,
validator: {
validate(value: any, args: ValidationArguments) {
return typeof value === 'string' && /.+@.+/.test(value);
},
},
});
};
}
class LoginForm {
@IsEmail()
public email!: string;
@MinLength(1)
@IsOptional()
public name: string | undefined;
@MinLength(8)
public password!: string;
}
const Login: React.FC = () => {
const [email, setEmail] = useState(''),
[name, setName] = useState<string | undefined>(),
[password, setPassword] = useState(''),
[errors, setErrors] = useState([]);
function sendLogin() {
if (errors.length !== 0) {
return;
}
const formEntity = plainToClass(LoginForm, { email, name, password }),
validationErrors = validateSync(formEntity);
if (validationErrors.length !== 0) {
setErrors(validationErrors);
return;
}
// Send the login form
}
return (
<form onSubmit={ sendLogin }>
<input type={ 'text' }
value={ email }
name={ 'email' }
onChange={ (event) => setEmail(event.currentTarget.value) }
/>
<input type={ 'text' }
value={ name }
name={ 'name' }
onChange={ (event) => {
let { value } = event.currentTarget;
if (value.length === 0) {
value = undefined;
}
setName(value);
} }
/>
<input type={ 'password' }
value={ password }
name={ 'password' }
onChange={ (event) => setPassword(event.currentTarget.value) }
/>
<button type={ 'submit' }>Login</button>
</form>
);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment