javascript – JS验证突出显示输入字段红色/绿色

前端之家收集整理的这篇文章主要介绍了javascript – JS验证突出显示输入字段红色/绿色前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在为我的 HTML表单创建一个简单的JS验证.验证检查字段是否为空,在某些情况下检查两者是否为空且输入!数字.这个检查很有效,但我想要实现的是如果JS检测到无效输入,则以红色突出显示该字段.如果输入无效,我已经编写了一些JS来设置输入字段的样式,但它是不起作用的突出显示.

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";
    }
}
原文链接:https://www.f2er.com/js/157432.html

猜你在找的JavaScript相关文章