javascriptlivevalidation

Live Validate Custom Validator


I'm following this example, http://livevalidation.com/documentation#ValidateCustom , to check if both fields are filled in. So if the first field is not blank the second one cannot be blank and vice versa.

Can anyone figure out why this code isn't working?

var txtFirstName = new LiveValidation('txtTaco', {onlyOnSubmit: true } );
txtFirstName.add( 
    Validate.Custom( 1, { against: function(value,args){
        if(args.first||args.last){
            if(args.first&&args.last){
                return true;
            } else {
                return false;
            }
        }
   }, 
   args: {
      first:txtTaco.value,
      last:lastName.value} 
   }) //end custom
); // end add

http://jsfiddle.net/r5X6P/


Solution

  • There were several issues with your question and fiddle:

    Working with the solution i found some issues with livevalidation:

    I did only one validator, for last name. When you change the first name it calls the last name validator. The downside is that if you style the border color of the invalid field, only last name will change.

    Here's the final code:

    var valLastName = new LiveValidation('txtLastName', {validMessage: " "});
    
    function validateFunction() {
        var first = txtFirstName.value;
        var last = txtLastName.value;
        if (first || last) // If either are present...
            return (first && last); // ...both must be present
        return true;
    }
    
    valLastName.add(Validate.Custom, {
        against: validateFunction, 
        failureMessage: "Please enter both first and last name", 
        displayMessageWhenEmpty: true
    });
    
    // Force validation of txtLastName
    txtFirstName.onkeyup = function() {txtLastName.onkeyup()}; 
    

    And fiddle: http://jsfiddle.net/P7Cf3/