0

I've written a jQuery validation rule that displays a failed validation if the amount entered into the input is less than 5000 or more than 500000. I'm trying to set the validation message to a variable to be dynamic in the rule but I'm getting an error saying I haven't defined my validationMessage variable.

# Error
Uncaught ReferenceError: validationMessage is not defined

# Custom Rule
$.validator.addMethod("requestAmount", function(value, element) {
  var cleanAmount = value.replace(/\,/g,'');
  var validationMessage = '';
  console.log(cleanAmount)
  if (cleanAmount < 5000) {
    var validationMessage = 'Please enter an amount greater than $5,000.00';
    return false;
  } else if (cleanAmount > 500000) {
    var validationMessage = 'Please enter an amount less than $500,000.00';
    return false;
  } else {
    return true;
  };
}, validationMessage);

1 Answer 1

1

Declare var validationMessage outside the function scope and remove the var from each time you set value to validationMessage:

var validationMessage;

# Custom Rule
$.validator.addMethod("requestAmount", function(value, element) {
  var cleanAmount = value.replace(/\,/g,'');
  validationMessage = '';
  console.log(cleanAmount)
  if (cleanAmount < 5000) {
    validationMessage = 'Please enter an amount greater than $5,000.00';
    return false;
  } else if (cleanAmount > 500000) {
    validationMessage = 'Please enter an amount less than $500,000.00';
    return false;
  } else {
    return true;
  };
}, function(){return validationMessage;});
Sign up to request clarification or add additional context in comments.

5 Comments

Ok I removed the vars from the function (makes sense). I also moved the var = validationMessage outside of the function. Now it's not showing blank messages for the validation- as if the variable isn't being reset in the function. Should I pass the variable into the function as an argument?
Yes, on the last row you send the validationMessage before you change it, so create the function(validationMessage) to solve the problem
I copy and pasted your solution to double check but I'm getting: Warning: No message defined for object_name[amount]
I don't really understand the code you added.. function() {return validationMessage;}) but it works. I'll have to dig into why this works.
When was there validationMessage, you send him as his before function(value, element) executed, but when there is a function, u send the function and it run after function(value, element) executed so you get the updated value.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.