Javascript验证突出显示字段

时间:2015-11-06 23:27:31

标签: javascript html

我正在为我的表单创建一个简单的JS验证。我需要它在未填写时突出显示红色onblur,然后在填充后将其填充为绿色。对不起,暂不允许在我的帖子中嵌入图片:L 感谢任何帮助,谢谢。

这是Html:

<form id="surveyForm">
Favourite movie?
    <input type="text" id="favMov" onblur="return $formValidation()"/>
    <span id="errorStyle"></span>
</form>

这是Js:

    function $formValidation(elem) {

        //gather the calling elements value
        var val = document.getElementById(elem.id).value;
        //Just for testing - alert(val.length);
        //if the length value of the text field is blank - show error
        if (val == "") {
            document.getElementById("errorStyle").style.borderColor = "red";
            return false
        } else {
            //if they are not blank remove error text
            document.getElementById("errorStyle").style.borderColor = "green";

        }
    }

你可以在这里找到一个小提琴样本:

http://jsfiddle.net/a45gn9w4/

1 个答案:

答案 0 :(得分:0)

您需要收听表单的提交并调用函数formValidation()

然后你可以实际获取这些元素并验证它是否正确。

这是html:

<form id="surveyForm" method="post" action="some_url_to_post">
    <label id="">Favourite movie?<span id="error" class="noErrorHappen">*</span></label>
    <input type="text" id="favMov" name="favMov">
    <br/>
    <input type="submit" id="validator" value="Submit">
</form>

这是js:

var error = document.getElementById("error");

var form = document.forms.surveyForm,
    elem = form.elements;


function formValidation() {
    if(!elem.favMov.value){
        alert('please input text.');
        elem.favMov.focus();
        error.className = "errorHappen";
        return false;
    } else {
        error.className = "noErrorHappen";
        return true;
    }
}



form.onsubmit = formValidation;

这是CSS:

.errorHappen {
  display: block;
  color: red;
}
.noErrorHappen {
  display: none;
}
#error {
    float: left;
}