[JavaScript]jQuery.validate 檢查文字長度

[JavaScript]jQuery.validate 檢查文字長度

參考:Count UTF-8 Bytes in a Form using JavaScript?

用jQuery.validation檢查UTF-8文字的位元數

image

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>jQuery validation plug-in - main demo</title>
 
 
<script src="jquery.js" type="text/javascript"></script>
<script src="jquery.validate.js" type="text/javascript"></script>
<script src="additional-methods.js" type="text/javascript"></script>
 
<script type="text/javascript">
function bytelength(str) {
    var escapedStr = encodeURI(str)
    if (escapedStr.indexOf("%") != -1) {
        var count = escapedStr.split("%").length - 1
        if (count == 0) count++  //perverse case; can't happen with real UTF-8
        var tmp = escapedStr.length - (count * 3)
        count = count + tmp
    } else {
        count = escapedStr.length
    }
    return count;
}
 
jQuery.validator.addMethod("maxBLen", function(value, element, blen) { 
  var len = bytelength(value);  
  return this.optional(element) || (blen >= len); 
});
 
$().ready(function() {
    $("#mainForm").validate({
        rules: {
            username: {
                required: true,
                maxlength: 6
            },
            memo: {
                required: true,                
                maxBLen: 6
            }
        },
        messages: {
            username: {
                required: "不可空白",
                maxlength: "過長"
            },
            memo:{
                required: "不可空白",
                maxBLen: "過長"
            }
        }
    });
});
 
 
</script>
</head>
<body>
 
<div id="main">
 
<form id="mainForm" method="get" action="">
    <fieldset>
        <legend>驗證表單</legend>
        <p>
            <label for="username">Username</label>
            <input id="username" name="username" />
        </p>
        <p>
            <label for="username">Memo</label>
            <input id="memo" name="memo" />
        </p>
        
        <p>
            <input class="submit" type="submit" value="送出"/>
        </p>
    </fieldset>
</form>
 
 
</div>
</body>
</html>