生活随笔
收集整理的這篇文章主要介紹了
限制输入字符串的长度
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
因?yàn)闈h字占兩個(gè)字節(jié),所以用String對(duì)象的Length屬性來(lái)獲取字符串長(zhǎng)度不合理,應(yīng)該使用String對(duì)象的charCodeAt()函數(shù),該函數(shù)可以將字符串中的指定字符轉(zhuǎn)換為Unicode編碼,通過(guò)字符的Unicode編碼范圍來(lái)判斷字符串中的漢字的長(zhǎng)度
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html><head><base href="<%=basePath%>"><title>限制輸入字符串的長(zhǎng)度</title><meta http-equiv="pragma" content="no-cache"><meta http-equiv="cache-control" content="no-cache"><meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"><meta http-equiv="description" content="This is my page"><!--<link rel="stylesheet" type="text/css" href="styles.css">--><script language="javascript"> /***限制輸入字符串的長(zhǎng)度*@ str:要判斷的字符串 *@ limitLength:限制的長(zhǎng)度*/function checkStrLength(str,limitLength){var n=0; //該變量保存字符串的長(zhǎng)度f(wàn)or(var i=0;i<str.length;i++){var code = str.charCodeAt(i);//獲得每個(gè)字符的Unicode值 if(code>255){n=n+2;}else{n=n+1;}}if(n>limitLength){ //如果字符串的長(zhǎng)度大于限制長(zhǎng)度,返回falsereturn false;}return true;}function check(){var userName = document.getElementById("username").value;var limitNum = 10;if(userName==""){alert("請(qǐng)輸入用戶名!");document.getElementById("username").focus();return;}if(!checkStrLength(userName,10)){alert("您輸入的用戶名不能超過(guò) "+limitNum/2+" 個(gè)字符!");return;}document.getElementById("myform").submit();}</script><style type="text/css">table{font-size: 13px;font-family: 楷體;color:navy;}input{font-size: 13px;font-family: 楷體;color:navy;}font{font-size: 12px;font-family: 楷體;color:orangered;}.style1{width: 500px;height: 160px;}</style></head><body><fieldset class="style1"><legend>用戶注冊(cè)</legend><form action="" id="myform"><table align="center"><tr><td>用戶名:</td><td><input type="text" id="username"> </td></tr> <tr><td>密碼:</td><td><input type="password" id="pwd"/></td></tr> <tr><td>確認(rèn)密碼:</td><td><input type="password" id="pwd1"/></td></tr> <tr><td>性別:</td><td><input type="radio" name="sex" id="man" value="m" checked="checked" />男<input type="radio" name="sex" id="woman" value="f" />女</td></tr> <tr><td>年齡:</td><td><input type="text" id="age"/></td></tr> <tr><td colspan="2" align="center"><input type="button" value="注 冊(cè)" "check()"></td></tr></table></form></fieldset></body>
</html>
總結(jié)
以上是生活随笔為你收集整理的限制输入字符串的长度的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
如果覺(jué)得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。