How to do jQuery validation to allow only english and japanese characters in the form

时光总嘲笑我的痴心妄想 提交于 2021-02-08 06:00:36

问题


In my form iam using jQuery validation plug-in to do validations to allow only English, but the problem now is the form text field now should allow English and Japanese only, all other characters should be omitted.

i did the validation for English characters but how to do the same for Japanese too. i have no idea how to do this. please help me iam a newbie.

my validation code for English is this :

<style>
  #nwsltrsnd label.error {
   color:red;
   }
   #nwsltrsnd input.error {
   border:1px solid red;
      }
    </style>
  <script>
   $(function() {
   $.validator.addMethod("accept", function(value, element, param) {
      return value.match(new RegExp("." + param + "$"));
      });
   $('#nwsltrsnd').validate({
           rules: { 
                name: { required: true, accept: "[a-zA-Z]+" },
                email: { required: true, email: true }},
           messages: { 
                name: {  required: "Name is required",
                accept: "Invalid name! either english/japanese allowed" },
                email: { required: "Email is required!" } 
            } }); });
    </script>

回答1:


you can use a custom validation rule with the regular expression,

Refer below,

Regular Expression for Japanese characters

Also, when I try below it works fine:

<!DOCTYPE html>
<html>
<link rel="stylesheet" type="text/css" href="css/bootstrap.css">
<script src="js/jquery.js"></script>
<script src="js/jquery.validate.js"></script>
<title>Validation Test</title>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />


</head>
<body>

<form id="validate-form">
    <table class="table">
        <tr>
            <td><input type="text" name="first_name" /></td>
        </tr>
        <tr>
            <td><input type="submit" name="submit" value="Validate" /></td>
        </tr>
    </table>
</form>

<script>
    $.validator.addMethod("languageTest", function(value) {
        //regEx = '/[一-龠]+|[ぁ-ゔ]+|[ァ-ヴー]+|[a-zA-Z0-9]+|[a-zA-Z0-9]+[々〆〤]+/u';
        regEx = /[一-龠]+|[ぁ-ゔ]+|[ァ-ヴー]+|[a-zA-Z0-9]+|[a-zA-Z0-9]+[々〆〤]+/;
        if(!regEx.test(value))
            return false;
        else if(regEx.test(value))
            return true;
    }, 'Please enter "anto"!');


    $("#validate-form").validate({
        rules : {
            first_name : {
                required : true,
                languageTest : true
            }
        },
        messages: {
            first_name : {
                required : 'Dont Leave it as blank',
                languageTest : 'Invalid language'
            }
        }
    });
</script>

<style>
.error{color:red;}
</style>
</body>
</html>


来源:https://stackoverflow.com/questions/31284335/how-to-do-jquery-validation-to-allow-only-english-and-japanese-characters-in-the

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!