当我尝试验证包含一组输入字段的表单时,最后一个输入字段未验证

时间:2017-03-21 11:25:02

标签: javascript forms

您好我是stackoverflow的新手,我正在新学习面向对象的JavaScript。我有四个输入文本字段,用于验证空内容。最后一个输入文本字段未验证。

<div class="errorMessage" id="errorMessage"></div>
    <form name="regForm" id="regForm" method="post" action="#">
        <fieldset>
            <legend>Registration Form</legend>
            <label>First Name: </label>
            <input type="text" id="fname" name="First Name"><br />
            <label>Last Name: </label>
            <input type="text" id="lname" name="Last Name"><br />
            <label>Email: </label>
            <input type="text" id="email"><br />
            <label>Mobile No:</label>
            <input type="text" id="mobileno"><br /><br />
            <button id="submit" onclick="return false">SUBMIT</button>
        </fieldset>
    </form>

Below starts the javascript function and input fields as parameters. Created a prototype function for the object InputFieldValidator and called that function on button click.

This is the object constructor 

function InputFieldValidator(inputFieldName) {
    this.inputFieldName = inputFieldName;
    this.fieldName = document.getElementById(this.inputFieldName);
    if(this.fieldName === 'undefined'){
        alert("No input field:" + this.inputFieldName);
    }
    this.inputFieldName = document.getElementById(this.inputFieldName).name;
}

prototype to the object

InputFieldValidator.prototype.validate = function(){

    var errorMessage = document.getElementById('errorMessage');

    if(this.fieldName.value === ""){
       errorMessage.style.display = 'block';
       errorMessage.innerHTML = "No field should be empty";   

    } else {
        errorMessage.style.display = 'none';
    }
};

on window load created the variables to the object and passed the id's of the input fields and to the variables i have called the validate prototype created above
window.onload = function(){

    var fnameValidator = new InputFieldValidator('fname'),
        lnameValidator = new InputFieldValidator('lname'),
        emailValidator = new InputFieldValidator('email'),
        mobileValidator = new InputFieldValidator('mobileno'),      
        submitButton = document.getElementById('submit');               

        submitButton.addEventListener('click', function(){
            fnameValidator.validate();
            lnameValidator.validate();  
            emailValidator.validate();  
            mobileValidator.validate();
        });
};

0 个答案:

没有答案