简体   繁体   中英

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/

There were several issues with your question and fiddle:

  • You included this link in the script section, which is the github page, not code.
  • You can't hotlink to github, to do this you need to use rawgithub.com
  • This validation is working only on the first text box, not the second
  • You are passing "1" as value to Custom, which is not being used
  • Your code don't include a <form> , so onlyOnSubmit will never trigger
  • Your <input> tags aren't closed
  • You don't need to if (condition) { return true } else { return false } , just return (condition)
  • You don't need to pass the values as args, just acquire them inside the function, it's cleaner and works just as well
  • Don't use obscure names like txtTaco

Working with the solution i found some issues with livevalidation:

  • You need to use an undocumented parameter displayMessageWhenEmpty to validate when the field is empty
  • There's a bug to hide the validMessage . According to comments on the source code, you need to set it to false to hide it, but this don't work. So I just set it to a space.

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/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM