jQuery Validator Custom Rules with passed-in messages

I'm trying to make my life easier using HTML5 tags to setup validation. I created a jQuery custom validation rule as follows:

jQuery.validator.addMethod("data-rule-usphone", function (value, element)
{
    return this.optional(element) || /^\(\d{3}\) \d{3}\-\d{4}( x\d{1,6})?$/.test(value);
}, "Please enter a valid phone number");

Open in new window


My HTML markup looks like this:

<input id="inputBusinessPhone" runat="server" placeholder="Business Phone" name="BusinessPhone" data-mask="(999) 999-9999" required data-rule-usphone="true" data-msg-usphone="Please enter the business telephone number" />

Open in new window


My question is how do I modify the jQuery validator custom function to use the value found in data-msg-usphone in the HTML markup? I'm not finding info online to do this.
LVL 22
Russ SuterSenior Software DeveloperAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Julian HansenCommented:
Your problem is that you are using hyphenated identifiers for your validator - this means that when you want to access the message for that validator you can't because hyphens are not valid in JavaScript property names.
This code should do what you require
<script type="text/javascript">
$(function() {
  $('form').validate({
    rules : {
      "BusinessPhone" : {
        required: true,
        BusinessPhone: true
      }
    }
  });
  
  jQuery.validator.addMethod("BusinessPhone", function (value, element)
  {
    jQuery.validator.messages.BusinessPhone = $(element).data('msg-usphone');
    return this.optional(element) || /^\(\d{3}\) \d{3}\-\d{4}( x\d{1,6})?$/.test(value);
  }, "Please enter a valid phone number");
});

Open in new window

Russ SuterSenior Software DeveloperAuthor Commented:
Hmmm... I'm using HTML5 markup. There must be a way for Javascript to recognize HTML5 markup which DOES use hyphens.
Julian HansenCommented:
Hyphens in property names is a JavaScript limitation - the hyphen is a minus sign and using it in a property name creates an unresolvable ambiguity

You can still access a property that internally is represented with hyphens using the quoted  index - in your case this would be something like this
  jQuery.validator.addMethod("data-rule-usphone", function (value, element)
  {
   // Note the reference using a quoted array index.
    jQuery.validator.messages["data-rule-usphone"] = $(element).data('msg-usphone');
    return this.optional(element) || /^\(\d{3}\) \d{3}\-\d{4}( x\d{1,6})?$/.test(value);
  }, "Please enter a valid phone number");

Open in new window

Big Business Goals? Which KPIs Will Help You

The most successful MSPs rely on metrics – known as key performance indicators (KPIs) – for making informed decisions that help their businesses thrive, rather than just survive. This eBook provides an overview of the most important KPIs used by top MSPs.

Russ SuterSenior Software DeveloperAuthor Commented:
OK. I tried your code suggestion but I still get the message "Please enter a valid phone number" rather than the custom message indicated by the data element "msg-usphone" so this doesn't work.
Julian HansenCommented:
Yes it does - refer sample below

http://www.marcorpsa.com/ee/t894.html

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Russ SuterSenior Software DeveloperAuthor Commented:
Had to make a minor change as follows:

jQuery.validator.addMethod("data-rule-usphone", function (value, element)
{
    if ($(element).data("msg-usphone") !== undefined)
    {
        jQuery.validator.messages["data-rule-usphone"] = $(element).data('msg-usphone');
    }
    else
    {
        jQuery.validator.messages["data-rule-usphone"] = "Please enter a valid phone number";
    }
    return this.optional(element) || /^\(\d{3}\) \d{3}\-\d{4}( x\d{1,6})?$/.test(value);
});

Open in new window


Otherwise if you don't specify the data-msg-usphone attribute you get a nasty error. The validator doesn't get to the string at the end.

But... with this change it is now working. Thanks!
Julian HansenCommented:
You are welcome.
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
jQuery

From novice to tech pro — start learning today.