Chlebta
Chlebta

Reputation: 3110

Form Validation Jquery Regular expression

this is my Script :

    <script type="text/javascript">
    $(document).ready(function () {
        $.validator.addMethod(
        "regex",
        function (value, element, regexp) {
            var re = new RegExp(regexp);
            return this.optional(element) || re.test(value);
        },
        "Matricule Invalide"
);
            $("form").validate({
                rules: {
                    idv: { required: true, regex: "/^(\d{3})TN(\d{4})$/" },
                    dd: { required: true },
                    df: { required: true },
                    remise: { required: true, range: [0, 100] }
                },
                messages: {
                  idv: { required:"champs requis", regex: "Matricule Invalide"},
                  dd: "champs requis",
                  df: "champs requis",
                  remise : { required: "champs requis",
                             range: "Valeur doit entre entre 0 et 100"}
                }
            });
        });
    </script>

The IDV field has to be like this way "111TN000" or "222TN0123" in other ways it's regular expression: Number of 3 digets +TN+ Number of Four digets. I have created my regular expression "/^(\d{3})TN(\d{4})$/", but the probleme here that when i put Valide IDV My Jquery Function show me always Matricule Invalide, This same Regulare expression works at Java and ASP.net.
I think i'm missing something very simple here?

Upvotes: 2

Views: 8166

Answers (2)

Rory McCrossan
Rory McCrossan

Reputation: 337550

Assuming you are using the jQuery validate regex plugin, as described in this question, you need to remove the leading/trailing slashes and escape the other slashes in your regex:

idv: { required: true, regex: "^(\\d{3})TN(\\d{4})$" }

Example fiddle


Alternatively, you can turn it into a regex object by removing the quotes around it:

idv: { required: true, regex: /^(\d{3})TN(\d{4})$/ }

Example fiddle

Upvotes: 4

refeline
refeline

Reputation: 39

I think you must delete slashes

"^(\d{3})TN(\d{4})$"

Upvotes: 0

Related Questions