简体   繁体   中英

How to do custom validation in JavaScript

I have a function that currently works with an input to prevent customers from inputting a PO Box into an address field. The input that works has an inline onKeyPress event, however the input I need to run the function on doesn't (and I can't access it).

My question is how to incorporate the correct event listener so that my function runs on this inaccessible input?

My JS Fiddle is here: http://jsfiddle.net/ZQQS9/4/

 function killPObox(id) { var idValue = document.getElementById('v65-onepage-shipaddr1').value; if (id == 'v65-onepage-shipaddr1') { function runVal() { if (idValue.substr(0,4).toUpperCase() === "PO B" || idValue.substr(0,5) === "PO ") { alert("USA Light cannot ship to PO Boxes. Please enter a street address."); } } setInterval(runVal(),1); } }
 <!-- Practice input that works --> 1. <input type="text" class="quantity" name="v65-onepage-shipaddr1" id="v65-onepage-shipaddr1" onKeyPress="killPObox(this.name)"> <br> <br> <!-- Actual input that I need to hook into, cannot edit --> 2. <input type="text" size="25" maxlength="75" name="ShipAddress1" id="v65-onepage-shipaddr1" value="" style="" onkeydown="">

You can use the addEventListener() method like this:

document.getElementById('v65-onepage-shipaddr2').addEventListener('keypress', killPObox('v65-onepage-shipaddr2'));

I think your first input is incorrectly passing this.name as the argument to the killPObox() function. Should you be passing this.id instead? Also you may want to replace 'v65-onepage-shipaddr1' in your killPObox() function to just id to use the argument passed into the function.

I'm sure you have solved this already, but since this is still unanswered (and I stumbled on it) I'll add the solution for future visitors.

Use the correct event
First off, the onKeyPress will actually fire before the typed character has been registered in the input element. So if a user types abc and you do onKeyPress="alert(this.value)" it would alert ab . A better alternative would be onKeyUp , since this would get the last typed character too.

Use the event correctly
Next, the events - your options are:

//inline, not considered "best practice"
<input type="text" name="myinput" id="myinput" onKeyUp="killPObox(this)"/>

//same event as above, but in pure js
document.getElementById('myinput').onkeyup = function (e) {
    killPObox(e.target);
};

//or attach an eventListener
document.getElementById('myinput').addEventListener('keyup', function (e) {
    killPObox(e.target)
});

All of these should work for the majority of browsers. I would suggest alternative 3, or if you need IE8 support, alternative 2.

The JavaScript, simplified
Your function, killPObox() , should look something like this (using one of the above events):

function killPObox(el) {
    if (el.id == 'v65-onepage-shipaddr1' || el.id == 'v65-onepage-shipaddr2') {
        if (el.value.substr(0, 4).toUpperCase() === "PO B" || el.value.substr(0, 5) === "P.O. ") {
            alert("USA Light cannot ship to P.O. Boxes. Please enter a street address.");
        }
    }
}  

Last but not least..
Finally, a very important part when using event binding, you need to use window.onload() . This is to make sure that both the script and elements that are to be bound are loaded before any code is run.

window.onload = function () {
    // my binds, events and calls here
};

An actual working example of all three events:

 function killPObox(el) { if (el.id == 'v65-onepage-shipaddr0' || el.id == 'v65-onepage-shipaddr1' || el.id == 'v65-onepage-shipaddr2') { if (el.value.substr(0, 4).toUpperCase() === "PO B" || el.value.substr(0, 5) === "PO ") { alert("USA Light cannot ship to PO Boxes. Please enter a street address."); } } } window.onload = function () { document.getElementById('v65-onepage-shipaddr1').onkeyup = function (e) { killPObox(e.target); }; document.getElementById('v65-onepage-shipaddr2').addEventListener('keyup', function (e) { killPObox(e.target) }); };
 "PO B" or "PO " will trigger the alert in all boxes:<br><br> 0. <input type="text" class="quantity" name="v65-onepage-shipaddr0" id="v65-onepage-shipaddr0" onKeyUp="killPObox(this)" /> <br/><br/> 1. <input type="text" class="quantity" name="v65-onepage-shipaddr1" id="v65-onepage-shipaddr1" /> <br/><br/> 2. <input type="text" class="quantity" name="v65-onepage-shipaddr2" id="v65-onepage-shipaddr2" />

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