简体   繁体   中英

JavaScript Form Validation on submit

I have a simple form and am validating onchange and need a final validation onsubmit. I am displaying a message to the right of the inputbox on error. I'm trying to keep this at DOM 1 compatible.

HTML

<form id = "myForm" action = "" onsubmit = "return validateForm(this);">
                <table class = "table-submit" border = "0">
                    <tr>
                        <td>
                            Username: 
                        </td>
                        <td>
                            <input type = "text" id = "username" 
                                size = "30" maxlength = "30"
                                onchange = "validateUsername(this, 'msgUsername')" />
                        </td>
                        <td id = "msgUsername">
                            &nbsp;
                        </td>
                    </tr>
                    <tr>
                        <td>
                            Password: 
                        </td>
                        <td>
                            <input type = "password" id = "password" 
                                size = "30" maxlength = "30"
                                onchange = "validatePassword(this, 'msgPassword')" />
                        </td>
                        <td id = "msgPassword">
                            &nbsp;
                        </td>
                    </tr>
                    <tr>
                    <td>&nbsp;</td>
                    <td>
                        &nbsp;
                        <input type = "submit" value = "Submit"  />
                        &nbsp;
                        <input type = "reset" value = "Clear" />
                    </td>
                </tr>
                </table>
</form>

JavaScript

function validateUsername(myItem, myElement) {
var dom = document.getElementById(myElement);

    if (myItem.value.length < 3) {
        dom.innerHTML = " Username needs to be a minimum of 3 characters! ";
        return false;
    }
    else {
        dom.innerHTML = "";
        return true;
    }
}

function validatePassword(myItem, myElement) {
var dom = document.getElementById(myElement);

    if (myItem.value.length < 5) {
        dom.innerHTML = " Password needs to be a minimum of 5 characters! ";
        return false;
    }
    else {
        dom.innerHTML = "";
        return true;
    }
}

function validateForm (itm) {

    // kind of stuck here...
}

As you may of noticed, I am a bit stuck on my validateForm() function. The code validates on each inputbox onchange event. Not sure what is the best way to go from here. I thought about doing an If for my both single input box validation, but I would need to send each parameters which is what i was trying to avoid by using this. Would like some suggestions.

Separate concerns. Instead of having the validate functions not only validate but also report your painting your self into a corner. Instead have a validate function which only returns true/false and another that is your onChange event handler which calls the validate function and displays the error message if needed. Then your onSubmit handler can easily call the validation functions in an if/else block to allow or cancel the submit action.

function validateUsername(username) {
  return username.length >= 3;
}

function validatePassword(password) {
  return password.length >= 5;
}

function showErrorFn(divId, message) {
  var div = document.getElementById(divId);
  message = " " + message;
  return function(message) {
    div.innerHTML = message;
  };
}

function makeChangeHandler(myItem, validationFn, errorFn) {
  return function(e) {
    if (validationFn(myItem.value)) {
      return true;
    } else {
      errorFn();
      return false;
    }
  };
}

function makeSubmitHandler(usernameEl, passwordEl) {
  return function(e) {
    if (validateUsername(usernameEl.value) && validatePassword(passwordEl.value)) {
      return true;
    } else {
      e.preventDefault();
      return false;
    }
}

var usernameEl = document.getElementById("username");
var usernameErrorEl = document.getElementById("msgUsername");
usernameEl.addEventListener("change", makeChangeHandler(
  usernameEl,
  validateUsername,
  showErrorFn("Username must be more then 3 characters")
);

var usernameEl = document.getElementById("password");
var usernameErrorEl = document.getElementById("msgPassword");
usernameEl.addEventListener("change", makeChangeHandler(
  usernameEl,
  validatePassword,
  showErrorFn("Password must be more then 5 characters")
);

var formEl = document.getElementById("myForm");
formEl.addEventListener("submit", makeSubmitHandler(usernameEl, password));

You can try this...

function validateForm (itm) {
    var flag = true;
    flag = (validateUsername(itm.username, 'msgUsername') && flag);
    flag = (validatePassword(itm.password, 'msgPassword') && flag);

return flag;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM