Skip to content

Instantly share code, notes, and snippets.

@coliveravenegas
Created March 14, 2017 01:16
Show Gist options
  • Save coliveravenegas/0851f3171ab0f224d29848d19c273028 to your computer and use it in GitHub Desktop.
Save coliveravenegas/0851f3171ab0f224d29848d19c273028 to your computer and use it in GitHub Desktop.
var React = require('react');
var Input = require('./Input');
var $ = require('zepto-browserify').$;
var validator = require('validator');
var cx = require('classnames');
require('../../../../scss/components/core/signup_form/SignUpForm.scss');
var SimpleRegisterForm = React.createClass({
getDefaultProps: function(){
return({
setActualForm: false,
oBackgroundColor: "#fff",
detailedRegisterForm: false,
hiddenFooter: false,
})
},
getInitialState: function() {
return {
emailPristiness: true,
passwordPristiness: true,
usernamePristiness: true,
emailDirtiness: false,
passwordDirtiness: false,
usernameDirtiness: false,
emailValidState: false,
passwordValidState: false,
usernameValidState: false,
emailLastErrorMessage: "",
passwordLastErrorMessage: "",
usernameLastErrorMessage: "",
uniqueEmailStatus: false,
uniqueUsernameStatus: false,
errorUsername: '',
forbiddenWords: ["password", "user", "username"],
loaderVisibility: false,
isRegisteringUser: false,
};
},
register: function(event){
let self = this;
event.preventDefault();
this.setState({
emailPristiness: false,
passwordPristiness: false,
usernamePristiness: false,
emailDirtiness: true,
passwordDirtiness: true,
usernameDirtiness: true,
}, this.triggerValidations);
if( self.state.emailValidState && self.state.passwordValidState && self.state.usernameValidState){
mixpanel.track("registerWithEmail");
self.setState({ isRegisteringUser: true });
$(".FooterRegisterForm__loader").show();
$.post( forms.register,
{ email: self.refs.email.value,
username: self.refs.username.value,
password: self.refs.password.value
}, function(response){
location.href = response;
}
);
return false;
}
// Disables the button to prevent forced registration
$(".FooterRegisterForm__loader").hide();
self.setState({ isRegisteringUser: false });
},
triggerValidations: function(){
this.validateUsername();
this.validateEmail();
this.validatePassword();
},
validateUsername: function(){
const USERNAME_PATTERN = /^[a-zA-Z0-9_-]{6,30}$/;
const NO_SPACES_PATTERN = /^\S+$/;
let username = this.refs.username.value;
//It will change pristiness to FALSE later based on Dirtiness status. DO NOT DELETE
if(!this.state.usernameDirtiness){
this.setState({ usernameDirtiness: true });
}
if(!this.state.usernamePristiness && this.state.usernameDirtiness){
//Starts the validation
if(username.length===0){
this.setState({ usernameValidState: false, usernameLastErrorMessage: "El campo usuario es obligatorio"});
}else if(username.length<6){
this.setState({ usernameValidState: false, usernameLastErrorMessage: "El usuario debe tener mínimo 6 caracteres"});
}else if(username.length>30){
this.setState({ usernameValidState: false, usernameLastErrorMessage: "El usuario debe tener máximo 30 caracteres"});
}else if( !validator.matches(username, USERNAME_PATTERN) ){
this.setState({ usernameValidState: false });
if( !validator.matches(username, NO_SPACES_PATTERN) ){
this.setState({usernameLastErrorMessage: "El nombre de usuario no puede contener espacios"});
}else{
this.setState({usernameLastErrorMessage: "El nombre de usuario no puede tener caracteres especiales como @, #, ¨¨"});
}
}
else{
this.setState({ usernameValidState: true });
this.checkUsernameAvailabilityService(username);
}
}
},
validatePassword: function(){
const PASSWORD_PATTERN = /^(?=.*[a-zA-Z0-9]).{6,50}$/;
let password = this.refs.password.value;
//It will change pristiness to FALSE later based on Dirtiness status. DO NOT DELETE
if(!this.state.passwordDirtiness){
this.setState({ passwordDirtiness: true });
}
if(!this.state.pristinePasswordStatus && this.state.passwordDirtiness){
//Starts the validation
if(password.length===0){
this.setState({ passwordValidState: false, passwordLastErrorMessage: "El campo contraseña es obligatorio"});
}else if( password.length<6){
this.setState({ passwordValidState: false, passwordLastErrorMessage: "La contraseña debe tener minimo 6 caracteres"});
}else if( password.length>50){
this.setState({ passwordValidState: false, passwordLastErrorMessage: "La contraseña debe tener maximo 50 caracteres"});
}else if( !validator.matches(password, PASSWORD_PATTERN) ){
this.setState({ passwordValidState: false, passwordLastErrorMessage: "La contraseña no puede contener espacios en blanco"});
}else{
this.setState({ passwordValidState: true});
}
}/*else{
return true;
}*/
},
validateEmail: function(){
const EMAIL_PATTERN = /^([a-zA-Z0-9_\.-]+)@([\da-zA-Z\.-]+)\.([a-zA-Z\.]{2,6})$/;
let email = this.refs.email.value;
//It will change pristiness to FALSE later based on Dirtiness status. DO NOT DELETE
if(!this.state.emailDirtiness){
this.setState({ emailDirtiness: true });
}
if(!this.state.emailPristiness && this.state.emailDirtiness){
//Starts the validation
if( email.length === 0 ){
this.setState({ emailValidState: false, emailLastErrorMessage: "El campo correo electrónico es obligatorio"});
}else if( !validator.matches(email, EMAIL_PATTERN) ){
this.setState({ emailValidState: false, emailLastErrorMessage: "Ingrese un correo electrónico válido"});
}
else{
this.setState({ emailValidState: true });
this.checkEmailAvailabilityService(email);
}
}
},
checkEmailAvailabilityService: function(email){
var self = this;
$.post('/validate-username-email/', { email: email, username: "" }, function(response){
if(response.email.status){
self.setState({ emailValidState: false, emailLastErrorMessage: "Ya existe un usuario con este correo electrónico"});
}
}, "json");
},
checkUsernameAvailabilityService: function(username){
var self = this;
$.post('/validate-username-email/', { username: username, email: "" }, function(response){
if(response.username.status){
self.setState({ usernameValidState: false, usernameLastErrorMessage: "Nombre de usuario no disponible"});
}
}, "json");
},
csrfValidation: function(){
if(next){
return(
<input type="hidden" value={ next } name="next" />
)
}else{
return(
<input type="hidden" value={courses_app} name="next" />
)
}
},
clearEmail: function () {
this.setState({
emailValidState: true,
emailPristiness: true
});
},
clearPassword: function () {
this.setState({
passwordValidState: true,
passwordPristiness: true
});
},
clearUsername: function () {
this.setState({
usernameValidState: true,
usernamePristiness: true
});
},
validateDuplicateEmail: function(){
var self= this;
if(this.refs.email.isValid()){
$.post('/validate-username-email/', { email: self.refs.email.getValue(), username: self.refs.username.getValue() }, function(response){
response = JSON.parse(response);
if(response.email.status == true){
self.refs.email.setBackendError(false, response.email.message);
self.setState({uniqueEmailStatus: false})
return false;
}else{
self.refs.email.setValid();
self.setState({uniqueEmailStatus: true})
return true;
}
});
}
},
validateDuplicateUsername: function(){
var self= this;
if(this.refs.username.isValid()){
$.post('/validate-username-email/', { email: self.refs.email.getValue(), username: self.refs.username.getValue() }, function(response){
response = JSON.parse(response);
if(response.username.status == true){
self.refs.username.setBackendError(false, response.username.message);
self.setState({uniqueUsernameStatus: false});
return false;
}else{
self.refs.username.setValid();
self.setState({uniqueUsernameStatus: true});
return true;
}
});
}
},
_openLogin: function(event){
event.preventDefault();
if(this.props.setActualForm){
this.props.setActualForm(2);
}else{
location.href = "/entrar";
}
},
handlePasswordBlur: function(){
if(this.state.passwordPristiness && this.state.passwordDirtiness){
this.setState({ passwordPristiness: !this.state.passwordDirtiness }, this.validatePassword);
}
},
handleEmailBlur: function(){
if(this.state.emailPristiness && this.state.emailDirtiness){
this.setState({ emailPristiness: !this.state.emailDirtiness }, this.validateEmail);
}
},
handleUsernameBlur: function(){
if(this.state.usernamePristiness && this.state.usernameDirtiness){
this.setState({ usernamePristiness: !this.state.usernameDirtiness }, this.validateUsername);
}
},
_showRegisterForm: function(){
$('.registerForm').show();
$('.registerWithEmailLabel').hide();
$('.buttons-container').css("margin-top", "0");
mixpanel.track("showRegisterForm");
},
_trackRegisterWithFacebook: function(){
mixpanel.track("registerWithFacebook");
},
componentDidMount: function(){
if(this.props.detailedRegisterForm){
this._showRegisterForm();
}
},
render: function() {
var email_container = cx(
'input-container'
,{'invalid' : !this.state.emailValidState && !this.state.emailPristiness}
,{'valid' : this.state.emailValidState && !this.state.emailPristiness}
);
var password_container = cx(
'input-container'
,{'invalid' : !this.state.passwordValidState && !this.state.passwordPristiness}
,{'valid' : this.state.passwordValidState && !this.state.passwordPristiness}
);
var username_container = cx(
'input-container'
,{'invalid' : !this.state.usernameValidState && !this.state.usernamePristiness}
,{'valid' : this.state.usernameValidState && !this.state.usernamePristiness}
);
let registerFormFooter = cx(
'registerFormFooter'
,{'isInvisible': this.props.hiddenFooter}
)
let FooterRegisterForm__registerButton = cx('FooterRegisterForm__registerButton', { 'isSendingForm' : this.state.isRegisteringUser })
return (
<section id="register-form">
<div className="signup-content">
<form id="registerForm">
<div className="registerForm">
<div className="validation-inputs">
<div className={email_container} >
<input ref="email" type="email" onBlur={this.handleEmailBlur} onChange={this.validateEmail} placeholder="Correo Electrónico" onFocus={this.clearEmail} />
<div className="error_message_container">
<p className="error_message"><img src="/static/img/footer/error-icon.png" alt="icono error" className="errorExclamationImage" />{this.state.emailLastErrorMessage}</p>
</div>
</div>
<div className={password_container} >
<input ref="password" type="password" onBlur={this.handlePasswordBlur} onChange={this.validatePassword} placeholder="Contraseña" onFocus={this.clearPassword} />
<div className="error_message_container">
<p className="error_message"><img src="/static/img/footer/error-icon.png" alt="icono error" className="errorExclamationImage" />{this.state.passwordLastErrorMessage}</p>
</div>
</div>
<div className={username_container} >
<input ref="username" type="text" onBlur={this.handleUsernameBlur} onChange={this.validateUsername} placeholder="Nombre de usuario" onFocus={this.clearUsername} />
<div className="error_message_container">
<p className="error_message"><img src="/static/img/footer/error-icon.png" alt="icono error" className="errorExclamationImage" />{this.state.usernameLastErrorMessage}</p>
</div>
</div>
</div>
<p className="FooterRegisterForm__terms">
Al registrarte, estás aceptando nuestros a <a href="#"className="FooterRegisterForm__termsLink">Términos y Condiciones</a>
</p>
<div className="FooterRegisterForm__registerButtonContainer" onClick={this.register}>
<button className={FooterRegisterForm__registerButton} >
Comienza un curso gratis
</button>
<img className="FooterRegisterForm__loader" src="/static/img/icon-loading.gif" alt="imagen cargando" />
</div>
</div>
</form>
</div>
</section>
);
}
});
export default SimpleRegisterForm;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment