非空验证,代码如下:
<form action="success.html" id="form">
<p>
用户名:<input type="text" name="nsername" id="username">
</p>
<input type="submit" value="提交">
</form>
<script>
let form = document.getElementById('form');
form.onsubmit = function(){
let user =document.getElementById('username').value;
//字符验证非空
if(user.trim() == ''){
alert('用户名不能为空');
return false
//阻止表单提交默认事件
}
}
验证邮箱,代码如下:
<form action="success.html" id="form">
<p>
邮箱:<input type="text" name="username" id="user">
</p>
<p>
密码:<input type="password" name="password" id="pwd">
</p>
<input type="submit" name="sub" id="sub" value="登录">
</form>
<script>
let form = document.getElementById('form');
form.onsubmit = function(){
let text = document.getElementById('user').value;
let pwd = document.getElementById('pwd').value;
if(text.trim() == ''){
alert('邮箱不能为空')
return false;
}
if(text.indexOf('@') == -1 || text.indexOf('.' == -1)){
alert('邮箱格式不正确')
return false
}
for(var i = 0;i < text.length;i++){
//每次循环只截取对应索引的一位,直到遍历完整个字符串
var j = text.substring(i,i+1)
if(isNaN[j] == false){
alert('不能有数字');
return false
}
}
if(pwd.trim() == ''){
alert('密码不能为空');
return false
}
return true;
}
</script>
文本框内容验证 代码如下:
<form action="" id="form">
<p>
用户名:
<input type="text" name="user" id="user">
</p>
<p>
<input type="text" id="pwd" name="pwd">
</p>
<p>
<input type="text" id="pwd2" name="pwd">
</p>
<input type="submit">
</form>
<script>
let form = document.getElementById('form');
form.onsubmit = function(){
let pwd1 = document.getElementById('pwd').value;
let pwd2 = document.getElementById('pwd2').value;
let user = document.getElementById('user').value;
if(pwd1.trim()== ''){
alert('密码不能为空');
return false
}
if(pwd1.length <6){
alert('密码不能少于6位');
return false
}
for(var i in pwd1){
if(isNaN(pwd1[i])==false){
alert('密码需要有数字')
}
return false
}
if(pwd2 !== pwd1){
alert('两次密码输入不一致')
return false
}
for(let i = 0;i < user.length; i++){
if(isNaN(user[i])==false){
alert('用户名不能有数字')
return false
}
}
return true;
}
</script>
文本框验证提示特效,代码如下:
<form action="success.html">
<p>
email:
<input type="text" name="email" id="eml" onblur="blurFn()">
<span></span>
</p>
<input type="submit" name="" id="" value="提交">
</form>
<script>
let form = document.querySelector('form');
let email = document.getElementById('eml');
let s = document.querySelector('span')
function blurFn(){
email.style.borderColor = 'red'
if(email.value.trim() ==''){
s.innerHTML = '密码不能为空';
s.style.color = 'red';
return false
}
email.style.borderColor = '';
s.innerHTML = '';
s.style.color = '';
return true;
}
form.onsubmit = function(){
if(blurFn()){
return true;
}
return false;
}
</script>