JavaScript基础(二)
##一、在平时我们需要验证输出的书否符合要求,那么数字如何去解决:
<body>
<h2>JavaScript 能够验证输入</h2>
<p>请输入 1 与 10 之间的数:</p>
<input id="numb">
<button type="button" onclick="myFunction()">提交</button>
<p id="demo"></p>
<script>
function myFunction() {
var x, text;
// 获取 id="numb" 的输入字段的值
x = document.getElementById("numb").value;
// 如果 x 不是数字或小于 1 或大于 10
if (isNaN(x) || x < 1 || x > 10) {
text = "输入无效";
} else {
text = "输入有效";
}
document.getElementById("demo").innerHTML = text;
}
</script>
</body>
##二、注册页面中,如何去验证输入的符合要求:
<tr>
<td class="td_left"><label for="username">用户名:</label></td>
<td class="td_right"><input type="text" name="username" id="username" placeholder="请输入用户名" onblur="checkUserName()">
<span id="s_username"class="error"style="color: red"></span>
</td>
</tr>
<tr>
<td class="td_left"><label for="password">密码:</label></td>
<td class="td_right"><input type="password" name="password" id="password" placeholder="请输入密码"onblur="checkPassWord()">
<span id="s_password"class="error"></span>
</td>
</tr>
那么我们在javaScript方法中的代码:
<script type="text/javascript">
function checkUserName() {
var username=document.getElementById("username").value;//获得username id的对象
var reg_username=/^w{6,12}$/;
var flag=reg_username.test(username);
var s_username=document.getElementById("s_username");
if(flag){
s_username.innerHTML="<img src='gou.png'>";
}else{
s_username.innerHTML="用户名格式错误";
}
}
function checkPassWord() {
var password=document.getElementById("password").value;
var reg_password=/^w{6,12}$/;
var flag=reg_password.test(password);
var s_password=document.getElementById("s_password");
if(flag){
s_password.innerHTML="<img src='gou.png'>";
}else{
s_password.innerHTML="密码格式错误,请重新输入";
}
}
</script>