24

Am using the JQuery Validator from http://bassistance.de/jquery-plugins/jquery-plugin-validation/. How can i make it so that the messages are custom and not in english.

Luis Alvarado
  • 8,837
  • 12
  • 46
  • 60

14 Answers14

37

If you look into the directory "localization", you could find different .js files that cointains error messages in different languages. [something like "messages_XX.js"]

Choose the file of the language you need and just add the following line, into the tag , after the inclusion of the jquery.validate.js

<script type="text/javascript" src="localization/messages_XX.js"></script>
andre_lost
  • 371
  • 1
  • 3
  • 4
  • This breaks the layout (popup message) i get in standard english. Now it adds plain text to my form which does not look nice. – Madmenyo Oct 26 '14 at 12:53
19

Do it like this:

$(document).ready(function() {
  $("form#login").validate({
    lang: 'en'  // or whatever language option you have.
  });
});

If the language you wish to supply is not one of the default languages, then do this:

$.tools.validator.localize("fi", {
    '*'          : 'Virheellinen arvo',
    ':email'     : 'Virheellinen s&auml;hk&ouml;postiosoite',
    ':number'    : 'Arvon on oltava numeerinen',
    ':url'       : 'Virheellinen URL',
    '[max]'      : 'Arvon on oltava pienempi, kuin $1',
    '[min]'      : 'Arvon on oltava suurempi, kuin $1',
    '[required]' : 'Kent&auml;n arvo on annettava'
});

  $("form#login").validate({
    lang: 'fi'
  });

See these instructions for more.

Dave Sag
  • 13,266
  • 14
  • 86
  • 134
  • 23
    These instructions are for the jQuery Tools Validator project, not jQuery Validate, which was asked about. – Tim Beadle Nov 29 '13 at 11:40
  • 2
    Link is not working could you update it :) and There is no lang option in jquery validator! :( – Alaeddine Jul 04 '16 at 14:36
  • 3
    For those who are looking for jquery validate plugin. Here is the answer http://stackoverflow.com/a/2457053/2265926 – Umar Sid Oct 14 '16 at 09:02
9

The best method is to extend the plugin like this when needed

$.extend($.validator.messages, {
    required: "my required message",
    ....
});
astroanu
  • 3,901
  • 2
  • 36
  • 50
5

Here would be your JSON structure in your initial validation script like Alex has:

   rules: {
        accntTypeCL: {
            required: true,
        },
        accntNoCL: {
            required: true,
            minlength: 19,
            numberDash: true,
        }
    },                      
    messages : {
        accntTypeCL : {
            required : Messages.ERR_TEST,
        },
        accntNoCL : {
            required : Messages.ERR_TEST,
            numberDash : Messages.ERR_TEST,
            minlength : Messages.ERR_TEST2,
        },
    }

//This would be in your messages.js file... But you'll need to make sure you are using a Java backend or something that will pull the messages.js correctly
//For IBM worklight this worked great       

    Messages = {
// Add here your messages for the default language. 
// Generate a similar file with a language suffix containing the translated messages

ERR_TOPLEVEL : '<span role=\"presentation\">One or more of the required fields was left blank or is invalid.<\/span>',
//Test Messages for tracing
ERR_TEST: 'This be the test yar!',
ERR_TEST2: 'This be the test2 yar!'
};

This way you can re-use the same functions, the same additional methods, and the same error types and just use the correct messages.js file based on the language of the html that should be detected in the browser or however you have it. This particular method worked good for me.

Community
  • 1
  • 1
isaac weathers
  • 1,436
  • 4
  • 27
  • 52
5

If you use npm / yarn to manage your assets, you can simply import the localization file like this (replace iso code of course, here it's french) :

import 'jquery-validation';
import 'jquery-validation/dist/localization/messages_fr';

Then use :

$form.validate({
    lang: 'fr',
});
Vincent Decaux
  • 9,857
  • 6
  • 56
  • 84
3

You could also put the error messages directly in the markup like this:

<input required data-msg="Please fill this field">
<input data-rule-minlength="2" data-rule-maxlength="4" data-msg-minlength="At least two chars" data-msg-maxlength="At most fours chars">

See documentation

If you use some kind of localization plugin, you can move the messages out in separate files. Here I use i18n-2 (npm module):

<input id="email" type="email" name="email" data-msg=__("pages.apply.form.email.errormsg.required"))

Then I put my language files in a folder:

/locales
    da.json
    en.json

en.json

"pages": {
        "apply": {
            "subtitle": "Apply here",
            "form": {
                    "email": {
                        "title": "Email",
                        "placeholder": "Your email address",
                        "warning": "NB! DER AFSENDES EN MAIL HERTIL",
                        "errormsg": {
                            "required": "Enter a valid email address"
                        }
                    }
             }
        }
 }
olefrank
  • 6,452
  • 14
  • 65
  • 90
3

Take look at my solution

jQuery.extend(jQuery.validator.messages, {
        required: abp.localization.localize("FormValidationMessageRequired"),//"This field is required.",
        remote: "Please fix this field.",
        email: abp.localization.localize("FormValidationMessageEmail"),//"Please enter a valid email address.",
        url: abp.localization.localize("FormValidationMessageUrl"),//"Please enter a valid URL.",
        date: abp.localization.localize("FormValidationMessageDate"),//"Please enter a valid date.",
        dateISO: "Please enter a valid date (ISO).",
        number:  abp.localization.localize("FormValidationMessageNumber"),//"Please enter a valid number.",
        digits: "Please enter only digits.",
        creditcard: "Please enter a valid credit card number.",
        equalTo:  abp.localization.localize("FormValidationMessageDataEquals"),//"Please enter the same value again.",
        accept: "Please enter a value with a valid extension.",
        maxlength: jQuery.validator.format("Please enter no more than {0} characters."),
        minlength: jQuery.validator.format(abp.localization.localize("FormValidationMessageMinlength")),//jQuery.validator.format("Please enter at least {0} characters."),
        rangelength: jQuery.validator.format("Please enter a value between {0} and {1} characters long."),
        range: jQuery.validator.format("Please enter a value between {0} and {1}."),
        max: jQuery.validator.format(abp.localization.localize("FormValidationMessageMax")),//jQuery.validator.format("Please enter a value less than or equal to {0}."),
        min: jQuery.validator.format(abp.localization.localize("FormValidationMessageMin"))//jQuery.validator.format("Please enter a value greater than or equal to {0}.")
    });

and this func abp.localization.localize(Key) return the localized string based on the current culture, this function is from the framework that I used called aspnetboilerplate

for more info see this stack overflow thread jQuery validation: change default error message

Community
  • 1
  • 1
Basheer AL-MOMANI
  • 14,473
  • 9
  • 96
  • 92
1

For the PHP i have done it like this.

$.validator.messages = $.extend({}, $.validator.messages, {
        required: '<?= __("This field is required.") ?>',
        remote: '<?= __("Please fix this field.") ?>',
        email: '<?= __("Please enter a valid email address.") ?>',
        url: '<?= __("Please enter a valid URL.") ?>',
        date: '<?= __("Please enter a valid date.") ?>',
        dateISO: '<?= __("Please enter a valid date (ISO).") ?>',
        number: '<?= __("Please enter a valid number.") ?>',
        digits: '<?= __("Please enter only digits.") ?>',
        equalTo: '<?= __("Please enter the same value again.") ?>',
        maxlength: $.validator.format( '<?= __("Please enter no more than {0} characters.") ?>' ),
        minlength: $.validator.format( '<?= __("Please enter at least {0} characters.") ?>' ),
        rangelength: $.validator.format( '<?= __("Please enter a value between {0} and {1} characters long.") ?>' ),
        range: $.validator.format( '<?= __("Please enter a value between {0} and {1}.") ?>' ),
        max: $.validator.format( '<?= __("Please enter a value less than or equal to {0}.") ?>' ),
        min: $.validator.format( '<?= __("Please enter a value greater than or equal to {0}.") ?>' ),
        step: $.validator.format( '<?= __("Please enter a multiple of {0}.") ?>' )
    })

So the languages changes as per the gettext these error messages also get change.

Vinod Raut
  • 63
  • 6
1

Use the messages object.

Key/value pairs defining custom messages. Key is the name of an element, value the message to display for that element. Instead of a plain message another map with specific messages for each rule can be used. Overrides the title attribute of an element or the default message for the method (in that order). Each message can be a String or a Callback. The callback is called in the scope of the validator and with the rule's parameters as the first and the element as the second arugment, it must return a String to display as the message.

Example

$(".selector").validate({
   rules: {
     name: "required",
     email: {
       required: true,
       email: true
     }
   },
   messages: {
     name: "Please specify your name",
     email: {
       required: "We need your email address to contact you",
       email: "Your email address must be in the format of name@domain.com"
     }
   }
})

Source.

alex
  • 479,566
  • 201
  • 878
  • 984
1

Here are the languages: https://cdn.jsdelivr.net/npm/jquery-validation@1.19.3/dist/localization/

Using ASP.NET WebForms, I have this in my Site.Master:

<script src="https://cdn.jsdelivr.net/npm/jquery-validation@1.19.3/dist/jquery.validate.js" type="text/javascript"></script>
<script src="https://cdn.jsdelivr.net/npm/jquery-validation@1.19.3/dist/localization/messages_es.js" type="text/javascript"></script>

Notice that the localization filename ends in es. Then in an .aspx file:

$('#myForm').validate({
   lang: 'es' // as the filename ends
});
netotz
  • 193
  • 1
  • 4
  • 12
0

This Worked for me :

 $.validator.messages.required = 'Your Message For required Fields ...';
 var validator = $("#formComplexe").validate();
 validator.form();

I have used this pluggin :

<script src="https://cdn.jsdelivr.net/npm/jquery-validation@1.19.2/dist/jquery.validate.js"></script>
Hicham O-Sfh
  • 731
  • 10
  • 12
0

You can use this in the footer.php

$.validator.messages = $.extend({}, $.validator.messages, {
required: '<?php _e("This field is required.","textDomain") ?>',
remote: '<?php _e("Please fix this field.","textDomain") ?>',
email: '<?php _e("Please enter a valid email address.","textDomain") ?>',
url: '<?php _e("Please enter a valid URL.","textDomain") ?>',
date: '<?php _e("Please enter a valid date.","textDomain") ?>',
dateISO: '<?php _e("Please enter a valid date (ISO).","textDomain") ?>',
number: '<?php _e("Please enter a valid number.","textDomain") ?>',
digits: '<?php _e("Please enter only digits.","textDomain") ?>',
equalTo: '<?php _e("Please enter the same value again.","textDomain") ?>',
maxlength: $.validator.format('<?php _e("Please enter no more than {0} characters.","textDomain") ?>'),
minlength: $.validator.format('<?php _e("Please enter at least {0} characters.","textDomain") ?>'),
rangelength: $.validator.format('<?php _e("Please enter a value between {0} and {1} characters long.","textDomain") ?>'),
range: $.validator.format('<?php _e("Please enter a value between {0} and {1}.","textDomain") ?>'),
max: $.validator.format('<?php _e("Please enter a value less than or equal to {0}.","textDomain") ?>'),
min: $.validator.format('<?php _e("Please enter a value greater than or equal to {0}.","textDomain") ?>'),
step: $.validator.format('<?php _e("Please enter a multiple of {0}.","textDomain") ?>')

});

-2

Late to the game, but if you're using the same template for multiple languages you can do it inline:

if($('html').attr('lang')=='he'){
    $('form').validate({
        messages: {
            email:  "חובה",
            phone:  "חובה",
            zip:    "חובה"
        }
    });
}else{
    $('form').validate({
        messages: {
            email:  "Required",
            phone:  "Required",
            zip:    "Required"
        }
    });
};
Heraldmonkey
  • 2,111
  • 2
  • 19
  • 29
-2

just enter a "required" value in the json that defines the validation. check the demos source, but its in the messages category

Jordan Wallwork
  • 3,116
  • 2
  • 24
  • 49