简体   繁体   中英

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?

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

我认为您必须删除斜杠

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

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