0

I am trying to come up with one function that can handle if statements in my code to avoid repetition of the same. For example in the code below

      // email
       App.Cmp.form.ValidateEmail = function(email) {
       var MyEmailId = document.getElementById(email);
       var format = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;

if (!MyEmailId.value.match(format)) {
    this.displayWarning(email, MyEmailId.parentNode.id, "Invalid email!");
} else {
    removeWarning(email, MyEmailId.parentNode.id);
    }
  }

  // password
  App.Cmp.form.ValidatePassword = function(password) {
  var MyPasswordId = document.getElementById(password);
  var format = /(?=^.{8,}$)(?=.*\d)(?=.*[!@#$%^&*]+)(?![.\n])(?=.*[A-Z])(?=.*[A-Z]).*$/;
if (!MyPasswordId.value.match(format)) {
    this
            .displayWarning(
                    password,
                    MyPasswordId.parentNode.id,
                    "The password must have uppercase, lowercase, numeric and special characters and at least 8 characters long");
} else {
    this.removeWarning(password, MyPasswordId.parentNode.id);
 }
}
  • 1
    What's the question? – Liam Jul 04 '16 at 10:52
  • 1
    You need to ask yourself is *"avoiding repetion"* a problem? There seems limited overlap between these methods. If they do different jobs they should BE different methods. If in doubt remember don't prematurly optimise and write you code to be easily read before optimising. ["Any fool can write code that a computer can understand. Good programmers write code that humans can understand"](http://stackoverflow.com/q/522828/542251) – Liam Jul 04 '16 at 10:54
  • You can avoid conditional branching in some cases by using polymorphism. To avoid repetition you can implement a functional solution. But it isn't the purpose of StackOverflow to present you a ready solution. –  Jul 04 '16 at 10:58

0 Answers0