Javascript 如何在特定框不为';我没有填写正确

Javascript 如何在特定框不为';我没有填写正确,javascript,html,css,Javascript,Html,Css,我正在尝试创建检查来验证用户的输入,例如他是否填写了它以及输入是否正确。我希望它突出显示包含错误的字段。 我已经问过了,有人告诉我创建一个类,但是我不知道怎么做。 还有 <!DOCTYPE HTML> <html lang="en"> <head> <title>Form Validation</title> <meta charset="utf-8"> <link rel="styleshee

我正在尝试创建检查来验证用户的输入,例如他是否填写了它以及输入是否正确。我希望它突出显示包含错误的字段。 我已经问过了,有人告诉我创建一个类,但是我不知道怎么做。 还有

<!DOCTYPE HTML>
<html lang="en">
<head>
    <title>Form Validation</title>
    <meta charset="utf-8">
    <link rel="stylesheet" type="text/css" href="styles/styles.css">
    <link rel="stylesheet" type="text/css" href="styles/forms.css">
    <script type="text/javascript">

    window.onload=init;
    var form;
        function init() {
            form = document.getElementById('testform');
            form.addEventListener("submit", checkSubmit, false);
            form.addEventListener("reset", checkReset, false);

            form['colour'].addEventListener("change", checkSubmit, false);

            form['name'].focus();
        }
        String.prototype.trim=function() {
            return this.replace(/^\s+1\s+$/g, '');
        }
        function whichButton(name) {
            var buttons=document.getElementsByName(name);
            for (var i in buttons) {
                if(buttons[i].checked) return buttons[i].value
            }
            return false;
        }
        function showOtherColour() {
            document.getElementById('othercolour').style.visibility=
                form['colour'].value=='other' ? 'visible' : 'hidden';
        }
        function checkSubmit() {
            error = new Array();
            //Fill the array with the error value

            form['name'].value=form['name'].value.trim();
            form['email'].value=form['email'].value.trim();
            form['town'].value=form['town'].value.trim();
            form['state'].value=form['state'].value.trim();
            form['postcode'].value=form['postcode'].value.trim();
            form['dob'].value=form['dob'].value.trim();
            form['height'].value=form['height'].value.trim();


            //Check required fields
            if(!form['name'].value)
                error.push('Missing Name');
            if(!form['email'].value)
                error.push('Missing Email Address');
            if(!form['password'].value)
                error.push('Missing Password');

            //Check valid email address
            var pattern=/^[a-zA-Z0-9._%-]+@[a-zA-Z0-9.-]+(\.[a-zA-Z]{2,4})$/;
            if(!form['email'].value.match(pattern))
                error.push('Invalid Email Address');

            //Check State

            //Check Post Code has 4 digits
            var pattern=/^\d{4}$/;
            if(!form['postcode'].value.match(pattern))
                error.push('Invalid Post Code');
            //Check password matches confirmation
            //var password = ;
            /*
            if(!form['passwordConfirm'].value.match(password)){
                error.push("Passwords don't match");
            }*/

            console.log(form['confirm'].value);
            console.log(form['password'].value);
            if(!form['confirm'].value.match(form['password'].value)){
                error.push('Passwords do not match');
            }
            //passwords is too short
            if (!form['password'].value.length < 4) {
                error.push("Password is too short (Minimum 4 characters)");
            }
            //height is not a number
            if (isNaN(Number(form['height'].value))) {
                error.push("Height is not a number");
            }
            //Check that one Gender item is selected
            if(whichButton('gender')===false)
                error.push('Please choose a Gender');

            //Check that "Other" field is filled
            if (!form['colour'].value ||
                (form['colour'].value=='other' && !form['othercolour'].value))
                error.push('Colour is not selected');

            if(error.length) { // if there are errors
            alert(error.join("\n"))
            return false;
            }
            else return true;

            //return confirm("This will submit the form"); //Temporary placeholder
        } 
        function checkReset() {
            return confirm("This will clear the form data");
        }
    </script>
<style type="text/css">
body,td,th {
    font-size: 0.9em;
}
</style>
</head>
<body>
<div id="body">
    <h1>Form Validation</h1>
    <form action="http://test.miform.net" method="post" id="testform">
    <fieldset>
        <label>Name<br><input type="text" name="name" class="wide"></label>
        <label>Email Address<br><input type="text" name="email" class="wide"></label>
    </fieldset>
    <fieldset>
        <label>Address<br><input type="text" name="street" class="wide"></label>
        <label>Town<br><input type="text" name="town" class="narrow"></label>
        <label>State<br><input type="text" name="state" class="narrow"></label>
        <label>PostCode<br><input type="text" name="postcode" class="narrow"></label>
    </fieldset>
    <fieldset>
        <label>Password<br><input type="password" name="password" class="medium"></label>
        <label>Confirm Password<br><input type="password" name="confirm" class="medium"></label>
    </fieldset>
    <fieldset>
        <label>Date of Birth<br><input type="text" name="dob" class="medium"></label>
        <label>Height<br><input type="text" name="height" class="medium"></label>
    </fieldset>
    <fieldset>
        <legend>Gender</legend>
        <label><input type="radio" name="gender" value="f">Female</label>
        <label><input type="radio" name="gender" value="m">Male</label>
    </fieldset>
    <fieldset>
        <label>Colour
            <select name="colour">
                <option value="">Select...</option>
                <option value="black">Black</option>
                <option value="white">White</option>
                <option value="red">Red</option>
                <option value="green">Green</option>
                <option value="blue">Blue</option>
                <option value="cyan">Cyan</option>
                <option value="magenta">Magenta</option>
                <option value="yellow">Yellow</option>
                <option value="other">Other</option>
            </select>
        </label>
        <input type="text" id="othercolour">
    </fieldset>
        <input type="reset" name="reset" value="Clear Form">
        <input type="submit" name="send" value="Send Off">
    </form>
</div>
</body>
</html>
style.css

body {
    font-family: sans-serif;
    font-size: .9em;
    background-color: rgb(166, 183, 183);
    color: black;
}
div#body {
    width: 30em;
    margin: auto;
    padding: 1em 2em;
    background-image: url(background.png);
    background-repeat: repeat-x;
    background-color: rgb(224, 230, 230);
}

h1,h2 {
    color: rgb(47, 79, 79);
}
h2 {
    margin: .25em 0em .25em 0em;
}
a {
    text-decoration: none;
    color: rgb(132, 156, 156);
    color: white;
    font-weight: bold;
}
a:hover {
    color: yellow;
}
td, th {
    vertical-align: top;
    text-align: left;
}
img {
    border: 0px;
}
p, .clear {
    qclear: both;
}
#catalog {
    float: left;
    width: 50%;
}
#content {
    float: right;
    width: 46%;
}
#cart {
    border: 1px solid #cccccc;
    padding: 0em .5em;
}
#cart form {
    display: inline;
}
#cart input.text {
    width: 2em;
    text-align: right;
}
#welcome {

}

#navigation {
}

#navigation span {
    color: rgb(131, 155, 155);
}

#navigation ul {
    list-style: none;
    padding: 0;
    margin: 0;
}
#navigation li {
    float: left;
    background-color: pink;
    border-bottom: solid 1px;
}
#navigation li a {
    display: block;
    width: 8em;
    text-decoration: none;
    font-weight: bold;
    text-align: center;
    padding: .25em;
    background-color: rgb(97, 124, 124);
}
#navigation li a:hover {
    background-color: rgb(47, 79, 79);
}

您可以设置
输入
的CSS属性以突出显示该字段

var input=document.querySelector('input'),
form=document.querySelector('form');
表.addEventListener('submit',函数(e){
e、 预防默认值();
如果(!input.value.trim()){//input的值为空
input.style.borderColor=“红色”;
}否则{
input.style.borderColor=“绿色”;
}
});


验证
要添加类,请使用JavaScript的
classList.add()
函数

示例

函数检查(){
var元素=document.getElementById(“输入”);
如果(element.value!=“”){
文件。写(“有效!”);
}否则{
元素.classList.add(“无效”);
}
}
。无效{
背景色:rgba(255,0,0,7);
颜色:白色;
}
.无效::占位符{
颜色:白色;
}


选中
如果使用HTML5验证属性,则只需使用:invalid pseudo类设置CSS规则:

:invalid { . . . }

你试过jQuery和Bootstrap吗?您只需几行代码就可以完成所有这一切,包括轻松更改长方体的颜色。
:invalid { . . . }