0

I have recently started following Javascript and that too Object Oriented JS and also i am impressed with Object Oriented JS except for its poor support for collections. Anyways getting back to the main topic..As an exercise i tried to create a Validation library for my application but it seems the instance values scopes are either not understood by me or else this is strange behavior. In order to illustrate this behavior i have sliced down the library to basic minimum in order to present here.

  • The below given sample validates if the email format is correct or not.

  • The problem is visible when you enter the correct format like
    johndoe@gmail.com and click submit.

  • It will trigger the registered event which modifies the IS_ERROR
    instance field to false and displayed by alert 1.

  • Then if you click the submit button the update function is triggered by onclick event of the submit button that tries to display the
    IS_ERROR value again as per the alert 2.

  • surprizingly these two values are different. How is that possible?
    What am i missing?

test.html

 <!DOCTYPE html>
<html>
<head>
<script src="validations.js"></script>
</head>
<body>  
  <form id="addEmailForm" action="/add/email" method="post">
        <div id="error"></div>
        Email <input type="email" id="email" name="email">
        <input type="button" onclick="update()" value="submit"></input>
  </form>
  <script>
    var registry = new ValidationRegistry(); 
    (
        function initialize(){

            var validation = new Validation("email",registry.EMAIL_VALIDATOR,"blur","error");
            registry.add(validation);

        }
    )();    

    function update(){
        alert("2 : "+registry.IS_ERROR);
        if(!registry.IS_ERROR){
            document.getElementById("addEmailForm").submit();
        }
    }
   </script>
</body>
</html> 

validations.js

function ValidationRegistry(){

    this.EMPTY_FIELD_VALIDATOR=1;
    this.UNIQUE_FIELD_VALIDATOR=2;
    this.FIELD_LENGTH_VALIDATOR=3;
    this.SPECIAL_CHAR_VALIDATOR=4;
    this.EMAIL_VALIDATOR=5;
    this.PHONE_VALIDATOR=6;
    this.IS_ERROR=true;
    this.factory;

    this.add=function(validation){

                var fieldId = validation.field;
                var validatorKey = validation.validator;                
                var event = validation.event;
                var errField = document.getElementById(validation.errField);
                var field = document.getElementById(fieldId);
                var result = null;

                field.addEventListener(event,function(){
                    this.factory = new ValidatorFactory();
                    var validator = this.factory.getValidator(validatorKey);

                    result = validator.validate(fieldId);

                    if(result!=true && errField!==null){
                            errField.style.color="#FF0000";                     
                            errField.innerHTML=result;
                            this.IS_ERROR=true;                         
                    }else{
                            this.IS_ERROR=false;
                            alert("1 : "+this.IS_ERROR);
                    }

                });

            }
}

function Validation(field,validator,event,errField){

    this.field=field;
    this.validator=validator;
    this.event=event;       
    this.errField=errField;

}


function ValidatorFactory(){
    this.getValidator=function(type){

    switch(type){

        case 5:
            return new EmailValidator();
            break;
        default:
            alert('default');
        }
    }
}       


function EmailValidator(){
    this.message="Invalid Email Id";
    this.validate=function(fieldId){                                
                        var value = document.getElementById(fieldId).value;                 
                        var regex = /(.*)@(.*)\.(.*)/;                              
                        if(regex.test(value)){
                            return true;
                        }
                        return this.message;
                    }
}
RaghaveShukla
  • 289
  • 6
  • 17
  • Yes somewhere related but then not very too the point and rather exaplanation are a little confusing. I would look for a simpler a solution and may be update it right here. – RaghaveShukla Jun 12 '15 at 12:16
  • The example in that question is directly analogous to your case: that question uses `transport.on` inside of a constructor; your question uses `field.addEventListener` inside of a constructor. The changes needed appear to be exactly the same. Where that solution uses `var self=this; transport.on('data', function() { alert(self.data); });`, you must use `var self=this; field.addEventListener(event,function(){ self.factory = ...` and `self.IS_ERROR`. – apsillers Jun 12 '15 at 12:41
  • @apsillers . Yes the explanations provided by the links you have mentioned are a match for this question. But i am not used to reading very long explanations. Any how the solution that you have provided is absolutely correct and now i understand why i need a `var self=this`. If you could open this question for answering may be i can provide a very crisp and short explanation which may be useful for those who expect a to the point answer. – RaghaveShukla Jun 13 '15 at 14:06

0 Answers0