Commit f5b65f3868e4b4d81bd4bbc5d1c78f7c557da50d

Authored by Leonardo Merlin
1 parent 571085f8

Add signup form validation (issue #340)

Showing 2 changed files with 137 additions and 72 deletions   Show diff stats
index.html
... ... @@ -429,11 +429,11 @@
429 429 <div class="row">
430 430 <div class="password col-sm-6">
431 431 <label for="signup-user_password" class="label">Senha:</label>
432   - <input id="signup-user_password" name="password" type="password" placeholder="Senha">
  432 + <input id="signup-user_password" name="password" required type="password" placeholder="Senha">
433 433 </div>
434 434 <div class="password-confirmation col-sm-6">
435 435 <label for="user_password_confirmation" class="label">Confirme a senha:</label>
436   - <input id="user_password_confirmation" name="password_confirmation" type="password" placeholder="Confirme a senha">
  436 + <input id="user_password_confirmation" name="password_confirmation" required type="password" placeholder="Confirme a senha">
437 437 </div>
438 438 <div class="oauth-providers">
439 439 <input id="user_oauth_providers" name="oauth_providers" type="hidden">
... ... @@ -443,9 +443,8 @@
443 443 </div>
444 444 <div id="terms-of-use-box" class="col-sm-12">
445 445 <div class="checkbox">
446   - <input id="user_terms_accepted" name="user[terms_accepted]" value="0" type="hidden" />
447   - <label>
448   - <input name="user[terms_accepted]" value="0" type="checkbox" />
  446 + <label for="user_terms_accepted">
  447 + <input id="user_terms_accepted" name="user_terms_accepted" value="0" required type="checkbox" />
449 448 Eu aceito os <a href="#/artigo/107880" target="_blank">termos de uso</a>
450 449 </label>
451 450 </div>
... ...
js/main.js
... ... @@ -251,12 +251,10 @@ define([&#39;jquery&#39;, &#39;handlebars&#39;, &#39;fastclick&#39;, &#39;handlebars_helpers&#39;, &#39;piwik&#39;], fun
251 251 var loginContainer = requireLoginContainer.find('.login-container');
252 252 loginContainer.show();
253 253 loginContainer.find('.new-user').click();
254   - var signupForm = loginContainer.find('#signup-form');
255   - signupForm.find('#user_email').val(user.email);
256   - signupForm.find('#user_name').val(user.login);
257   - signupForm.find('#user_oauth_providers').val(user.oauth_providers);
258   - //signupForm.find(".password").hide();
259   - //signupForm.find(".password-confirmation").hide();
  254 + var $signupForm = loginContainer.find('#signup-form');
  255 + $signupForm.find('#user_email').val(user.email);
  256 + $signupForm.find('#user_name').val(user.login);
  257 + $signupForm.find('#user_oauth_providers').val(user.oauth_providers);
260 258 } else {
261 259 requireLoginContainer.find('.require-login').hide();
262 260 requireLoginContainer.find('.login-container').show();
... ... @@ -1026,16 +1024,16 @@ define([&#39;jquery&#39;, &#39;handlebars&#39;, &#39;fastclick&#39;, &#39;handlebars_helpers&#39;, &#39;piwik&#39;], fun
1026 1024 var proposal_id = this.id.split('-').pop();
1027 1025 var form = this;
1028 1026 var $form = $(this);
1029   - var message = $(form).find('.message');
1030   - message.hide();
1031   - message.text('');
  1027 + var $message = $form.find('.message');
  1028 + $message.hide();
  1029 + $message.text('');
1032 1030 $.ajax({
1033 1031 type: 'post',
1034 1032 url: host + $form.attr('action'),
1035   - data: $('#'+this.id).serialize() + '&private_token=' + Main.private_token + '&fields=id&article[name]=article_' + Main.guid()
  1033 + data: $form.serialize() + '&private_token=' + Main.private_token + '&fields=id&article[name]=article_' + Main.guid()
1036 1034 })
1037 1035 .done(function( /*data*/ ) {
1038   - form.reset();
  1036 + $form.reset();
1039 1037 $form.hide();
1040 1038 $form.siblings('.success-sent').show();
1041 1039 $form.siblings('.subtitle').hide();
... ... @@ -1044,15 +1042,15 @@ define([&#39;jquery&#39;, &#39;handlebars&#39;, &#39;fastclick&#39;, &#39;handlebars_helpers&#39;, &#39;piwik&#39;], fun
1044 1042 })
1045 1043 .fail(function( jqxhr, textStatus, error ) {
1046 1044 var err = textStatus + ', ' + error;
1047   - console.log( 'Request Failed: ' + err );
1048   - message.show();
1049   - message.text('Não foi possível enviar.');
  1045 + // console.log( 'Request Failed: ' + err );
  1046 + $message.show();
  1047 + $message.text('Não foi possível enviar.');
1050 1048 });
1051 1049 });
1052 1050 })
1053 1051 .fail(function( jqxhr, textStatus, error ) {
1054 1052 var err = textStatus + ', ' + error;
1055   - console.log( 'Request Failed: ' + err );
  1053 + // console.log( 'Request Failed: ' + err );
1056 1054 });
1057 1055  
1058 1056 $(document).ready(function($) {
... ... @@ -1088,7 +1086,6 @@ define([&#39;jquery&#39;, &#39;handlebars&#39;, &#39;fastclick&#39;, &#39;handlebars_helpers&#39;, &#39;piwik&#39;], fun
1088 1086  
1089 1087 $(document).on('click', '.login-action', function(e) {
1090 1088 e.preventDefault();
1091   - // console.log('obj', obj);
1092 1089  
1093 1090 var $this = $(this); // button
1094 1091 var $form = $this.closest('#login-form');
... ... @@ -1146,7 +1143,6 @@ define([&#39;jquery&#39;, &#39;handlebars&#39;, &#39;fastclick&#39;, &#39;handlebars_helpers&#39;, &#39;piwik&#39;], fun
1146 1143 var loginForm = $(this).parents('#login-form');
1147 1144 var signupForm = loginForm.siblings('#signup-form');
1148 1145 window.signupForm = signupForm;
1149   - // console.log("novo usuário");
1150 1146 loginForm.hide();
1151 1147 signupForm.show();
1152 1148 signupForm.find(".password").show();
... ... @@ -1165,60 +1161,137 @@ define([&#39;jquery&#39;, &#39;handlebars&#39;, &#39;fastclick&#39;, &#39;handlebars_helpers&#39;, &#39;piwik&#39;], fun
1165 1161 });
1166 1162  
1167 1163 $(document).on('click', '.confirm-signup', function(e) {
  1164 +
  1165 + var $button = $(this);
  1166 + var $signupForm = $(this).parents('form.signup');
  1167 + var $inputEmail = $signupForm.find('#signup-user_email');
  1168 + var $inputUsername = $signupForm.find('#signup-user_name');
  1169 + var $inputPassword = $signupForm.find('#signup-user_password');
  1170 + var $inputPasswordConfirmation = $signupForm.find('#user_password_confirmation');
  1171 + var $inputAcceptation = $signupForm.find('#user_terms_accepted');
  1172 + var $inputCaptcha = $signupForm.find('#recaptcha_response_field');
  1173 +
  1174 + // clear messages
1168 1175 var message = $('.signup .message');
1169 1176 message.hide();
1170 1177 message.text('');
1171 1178  
1172   - var signup = $(this).parents('form.signup');
1173   - var $loading = $('.login-container .loading');
1174   - $loading.show();
1175   - signup.hide();
1176   - signup.removeClass('hide');
1177   - var button = $(this);
  1179 + // Validate form
  1180 + var hasEmail = $inputEmail && $inputEmail.val().length > 0;
  1181 + var hasUsername = $inputUsername && $inputUsername.val().length > 0;
  1182 + var hasPassword = $inputPassword && $inputPassword.val().length > 0;
  1183 + var hasPasswordConfirmation = $inputPasswordConfirmation && $inputPasswordConfirmation.val().length > 0;
  1184 + var hasPasswordEquals = $inputPassword.val() == $inputPasswordConfirmation.val();
  1185 + var hasAcceptation = $inputAcceptation.val();
  1186 + var hasCaptcha = $inputCaptcha.val().length > 0;
  1187 + var hasError = (!hasEmail || !hasUsername || !hasPassword || !hasPasswordConfirmation || !hasPasswordEquals || !hasAcceptation || !hasCaptcha);
1178 1188  
1179   - $.ajax({
1180   - type: 'post',
1181   - url: host + '/api/v1/register',
1182   - data: $(this).parents('.signup').serialize(),
1183   - }).done(function(data) {
  1189 + if(hasError){
1184 1190  
1185   - var $sectionContent = button.closest('.section-content');
1186   - if($sectionContent && $sectionContent.length > 0){
1187   - Main.displaySuccess($sectionContent, 'Cadastro efetuado com sucesso', 1000, 'icon-user-created');
  1191 + if ($signupForm[0].checkValidity()) { // force check of HTML5 validation
  1192 + e.preventDefault();
  1193 +
  1194 + var messageErrors = [];
  1195 +
  1196 + messageErrors.push('<ul>'); // start a HTML list
  1197 +
  1198 + if (!hasEmail){
  1199 + messageErrors.push('<li>O e-mail é um campo obrigatório.</li>');
  1200 + }
  1201 +
  1202 + if (!hasUsername){
  1203 + messageErrors.push('<li>O nome de usuário é um campo obrigatório.</li>');
  1204 + }
  1205 +
  1206 + if (!hasPassword){
  1207 + messageErrors.push('<li>A senha é um campo obrigatório.</li>');
  1208 + }
  1209 +
  1210 + if (!hasPasswordConfirmation){
  1211 + messageErrors.push('<li>A confirmação da senha é um campo obrigatório.</li>');
  1212 + }
  1213 +
  1214 + if (!hasPasswordEquals){
  1215 + messageErrors.push('<li>A senha e confirmação da senha devem ser iguais.</li>');
  1216 + }
  1217 +
  1218 + if (!hasAcceptation){
  1219 + messageErrors.push('<li>Você deve ler e aceitar os termos de uso.</li>');
  1220 + }
  1221 +
  1222 + if (!hasCaptcha){
  1223 + messageErrors.push('<li>O ReCaptcha é um campo obrigatório.</li>');
  1224 + }
  1225 +
  1226 + messageErrors.push('</ul>'); // close the paragraph
  1227 +
  1228 + messageErrors = messageErrors.join('<br/>');
  1229 + message.html($(messageErrors));
  1230 + message.show();
1188 1231 }
  1232 + } else {
  1233 + e.preventDefault();
1189 1234  
1190   - $(document).trigger('login:success', data);
1191   - }).fail(function(data) {
1192   - var msg = "";
1193   - window.signupForm.find('#g-recaptcha').empty();
1194   - Recaptcha.create(window.recaptchaSiteKey, window.signupForm.find('#g-recaptcha')[0], { lang : 'pt', theme: "clean", callback: Recaptcha.focus_response_field } );
1195   -
1196   - try{
1197   - msg = Main.responseToText(data.responseJSON.message);
1198   - }catch(ex){
1199   - var ptBR = {};
1200   - // (Invalid request) email can't be saved
1201   - ptBR['(Invalid request) email can\'t be saved'] = 'E-mail inválido.';
1202   - // (Invalid request) login can't be saved
1203   - ptBR['(Invalid request) login can\'t be saved'] = 'Nome de usuário inválido.';
1204   - ptBR['Please solve the test in order to register.'] = 'Por favor, digite os caracteres da imagem na caixa abaixo dela.';
1205   - msg = ptBR[data.responseJSON.message] || data.responseJSON.message;
  1235 + // show loading
  1236 + var $loading = $('.login-container .loading');
  1237 + $loading.show();
  1238 +
  1239 + $.ajax({
  1240 + type: 'post',
  1241 + url: host + '/api/v1/register',
  1242 + data: $signupForm.serialize(),
  1243 + })
  1244 + .done(handleDone)
  1245 + .fail(handleFail)
  1246 + .always(handleAlways);
  1247 +
  1248 + function handleDone(data){
  1249 +
  1250 + $signupForm.hide();
  1251 + $signupForm.removeClass('hide');
  1252 +
  1253 + var $sectionContent = $button.closest('.section-content');
  1254 + if($sectionContent && $sectionContent.length > 0){
  1255 + Main.displaySuccess($sectionContent, 'Cadastro efetuado com sucesso', 1000, 'icon-user-created');
  1256 + }
  1257 +
  1258 + $(document).trigger('login:success', data);
1206 1259 }
1207 1260  
1208   - message.show();
1209   - message.html('Não foi possível efetuar o cadastro: <br/><br/>' + msg);
  1261 + function handleFail(data, var2) {
  1262 + var msg = "";
  1263 + $signupForm.find('#g-recaptcha').empty();
  1264 + Recaptcha.create(window.recaptchaSiteKey, $signupForm.find('#g-recaptcha')[0], { lang : 'pt', theme: "clean", callback: Recaptcha.focus_response_field } );
  1265 +
  1266 + if(data.responseJSON){
  1267 + try{
  1268 + msg = Main.responseToText(data.responseJSON.message);
  1269 + }catch(ex){
  1270 + var ptBR = {};
  1271 + // (Invalid request) email can't be saved
  1272 + ptBR['(Invalid request) email can\'t be saved'] = 'E-mail inválido.';
  1273 + // (Invalid request) login can't be saved
  1274 + ptBR['(Invalid request) login can\'t be saved'] = 'Nome de usuário inválido.';
  1275 + ptBR['Please solve the test in order to register.'] = 'Por favor, digite os caracteres da imagem na caixa abaixo dela.';
  1276 + msg = '<br/><br/>';
  1277 + msg += ptBR[data.responseJSON.message] || data.responseJSON.message;
  1278 + }
  1279 + }else{
  1280 + msg = '<br/><br/>';
  1281 + msg += 'Erro na comunicação com o servidor.';
  1282 + }
1210 1283  
1211   - $(document).trigger('login:fail', data);
1212   - }).always(function() {
1213   - $loading.hide();
1214   - signup.show();
  1284 + message.html('<p>Não foi possível efetuar o cadastro:' + msg + '</p>');
  1285 + message.show();
1215 1286  
1216   - // var $loginPanel = $loading.closest('#login-panel');
1217   - // if($loginPanel && $loginPanel.length > 0){
1218   - // $loginPanel.hide();
1219   - // }
1220   - });
1221   - e.preventDefault();
  1287 + $(document).trigger('login:fail', data);
  1288 + }
  1289 +
  1290 + function handleAlways() {
  1291 + $loading.hide();
  1292 + signup.show();
  1293 + }
  1294 + }
1222 1295 });
1223 1296  
1224 1297 // var popupCenter = function(url, title, w, h) {
... ... @@ -1268,8 +1341,6 @@ define([&#39;jquery&#39;, &#39;handlebars&#39;, &#39;fastclick&#39;, &#39;handlebars_helpers&#39;, &#39;piwik&#39;], fun
1268 1341 var url = $iframe.attr('src');
1269 1342 var c = '?';
1270 1343  
1271   - // console.log('url', url);
1272   - // console.log('url.indexOf("youtube")', url.indexOf("youtube"));
1273 1344 if(url.indexOf("youtube") === -1){
1274 1345 // is not a iframe of youtube
1275 1346 // console.debug('is not a iframe of youtube');
... ... @@ -1293,11 +1364,6 @@ define([&#39;jquery&#39;, &#39;handlebars&#39;, &#39;fastclick&#39;, &#39;handlebars_helpers&#39;, &#39;piwik&#39;], fun
1293 1364 setTimeout(checkIframes, 500);
1294 1365 }
1295 1366 checkIframes();
1296   - // $(document).bind('DOMSubtreeModified', function(e){
1297   - // console.log('this', this);
1298   - // console.log('e', e);
1299   -
1300   - // });
1301 1367  
1302 1368 });
1303 1369  
... ... @@ -1313,7 +1379,7 @@ define([&#39;jquery&#39;, &#39;handlebars&#39;, &#39;fastclick&#39;, &#39;handlebars_helpers&#39;, &#39;piwik&#39;], fun
1313 1379 Main.locationHashChanged.apply(Main);
1314 1380 }
1315 1381 }else{
1316   - console.log('The browser not supports the hashchange event!');
  1382 + // console.log('The browser not supports the hashchange event!');
1317 1383 }
1318 1384  
1319 1385 // Handle resize event
... ...