Skip to content

Instantly share code, notes, and snippets.

@sofyan-ahmad
Created December 28, 2017 08:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sofyan-ahmad/3f04600fe973a1c9abd9184379551e40 to your computer and use it in GitHub Desktop.
Save sofyan-ahmad/3f04600fe973a1c9abd9184379551e40 to your computer and use it in GitHub Desktop.
import { action, observable } from 'mobx';
class LoginStore {
@observable public email = '';
@observable public password = '';
@observable public isValid = false;
@observable public emailError : string | undefined = '';
@observable public passwordError : string | undefined = '';
@action
public emailOnChange(id: string) {
this.email = id;
this.validateEmail();
}
@action
public validateEmail() {
const emailPatter = /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i;
const required = this.email ? undefined : 'Required';
this.emailError = required
? required
: emailPatter.test(this.email) ? undefined : 'Invalid email address';
}
@action
public passwordOnChange(pwd: string) {
this.password = pwd;
this.validatePassword();
}
@action
public validatePassword() {
const alphaNumeric = /[^a-zA-Z0-9 ]/i.test(this.password)
? 'Only alphanumeric characters'
: undefined;
const maxLength =
this.password.length > 15 ? 'Must be 15 characters or less' : undefined;
const minLength =
this.password.length < 8 ? 'Must be 8 characters or more' : undefined;
const required = this.password ? undefined : 'Required';
this.passwordError = required
? required
: alphaNumeric ? alphaNumeric : maxLength ? maxLength : minLength;
}
@action
public validateForm() {
if (this.emailError === undefined && this.passwordError === undefined) {
this.isValid = true;
}
}
@action
public clearStore() {
this.email = '';
this.isValid = false;
this.emailError = '';
this.password = '';
this.passwordError = '';
}
}
export default LoginStore;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment