Phase 2 : Week 5 : Thursday
I've probably said "wait, wtf am I doing?" this week, more than any other time in my life. Embracing confusion can be easier said than done.
Thanks to the many hours of help I sought after with TA's Matt, Josh, and my instructor Anne, I'm starting to embrace this JS prototype and OOD business. Of course, there are things I'd like to change (like using .test() instead of .match()).
The challenge was to validate html form inputs, and display the validation errors by modifying JS only:
function Validator(){ this.errors = []; this.valid = true }; Validator.prototype.eval_input = function(input, format, message){ if (input.match(format) == null ){ this.errors.push(message); this.valid = false; } } Validator.prototype.checkEmail = function(email){ var format = /^\w+@[a-zA-Z_]+?\.[a-zA-Z]{2,3}$/ var message = "Must be a valid email" this.eval_input(email, format, message); }; Validator.prototype.validate = function(email, password){ this.checkEmail(email); }; Validator.prototype.show_errors = function(){ $.each(this.errors, function(index, value){ $('#errors').append("<li>" + value + "</li>"); }); validator.valid = true; validator.errors = []; } $(function(){ validator = new Validator(); $('form').on('submit', function(e){ e.preventDefault(); $('#errors').empty(); var email = $(':input[type="text"]').val(); var pswd = $(':input[type="password"]').val(); validator.validate(email, pswd); if (validator.valid == false) { validator.show_errors(); } else { $(this).unbind('submit').submit(); }; }); });








