我正在为我的
HTML表单创建一个简单的JS验证.验证检查字段是否为空,在某些情况下检查两者是否为空且输入!数字.这个检查很有效,但我想要实现的是如果JS检测到无效输入,则以红色突出显示该字段.如果输入无效,我已经编写了一些JS来设置输入字段的样式,但它是不起作用的突出显示.
@H_502_13@解决方法
JS snap
function FormValidation(){ //First Name Validation var fn=document.getElementById('firstname').value; if(fn == ""){ alert('Please Enter First Name'); document.getElementById('firstname').style.borderColor = "red"; return false; }else{ document.getElementById('firstname').style.borderColor = "green"; } if (/^[0-9]+$/.test(document.getElementById("firstname").value)) { alert("First Name Contains Numbers!"); document.getElementById('firstname').style.borderColor = "red"; return false; }else{ document.getElementById('firstname').style.borderColor = "green"; } if(fn.length <=2){ alert('Your Name is To Short'); document.getElementById('firstname').style.borderColor = "red"; return false; }else{ document.getElementById('firstname').style.borderColor = "green"; }
HTML快照
<form action="" method="post" onsubmit="return FormValidation();" onchange="return FormValidation();"> <div class="input-wrapper"> <input type="text" placeholder="First Name" id="firstname" name="name"/> </div> </form>
我很确定这个亮点应该有效.我之前做过类似的验证,但不幸的是,这次我无法得到我追求的结果.
你最后错过了一个},但除此之外,似乎工作得很好.
这是一个工作小提琴:http://jsfiddle.net/aJ2Tw/
function FormValidation(){ //First Name Validation var fn=document.getElementById('firstname').value; if(fn == ""){ alert('Please Enter First Name'); document.getElementById('firstname').style.borderColor = "red"; return false; }else{ document.getElementById('firstname').style.borderColor = "green"; } if (/^[0-9]+$/.test(document.getElementById("firstname").value)) { alert("First Name Contains Numbers!"); document.getElementById('firstname').style.borderColor = "red"; return false; }else{ document.getElementById('firstname').style.borderColor = "green"; } if(fn.length <=2){ alert('Your Name is To Short'); document.getElementById('firstname').style.borderColor = "red"; return false; }else{ document.getElementById('firstname').style.borderColor = "green"; } }