简体   繁体   中英

jquery run conditional validation inside .on

I have a form with the ID #primarySearch . It has 3 text inputs, all of which have their own ID as follows: #ecNumber , #casNumber , #substanceName .

I have the following js. If the user enters anything in a text input in #primarySearch it runs a function called processPrimarySearch and sends the appropriate input value to it:

$('#primarySearch input[type="text"]').on({
    "keyup": function(e) {
      // Ignore tab key 
      if (e.which != 9) {
        processPrimarySearch.call(this);
      }
    }
});

function processPrimarySearch() {
   // ...
}

I've also got some other js (which is just inside document.ready ) which stops the user entering anything other than numbers and dashes - but only in the #ecNumber and #casNumber fields (please note I adapted this from jQuery only allow numbers,letters and hyphens ). Although this code fires if the user is entering things into these 2 fields, it also results in processPrimarySearch running irrespective of whether the user input is valid. This is because there is no connection between the code above, and the following code:

$('#ecNumber, #casNumber').keypress(function (e) {
    var allowedChars = new RegExp("^[0-9\-]+$");
    var str = String.fromCharCode(!e.charCode ? e.which : e.charCode);
    if (allowedChars.test(str)) {
        return true;
    }
    e.preventDefault();
    return false;
}).keyup(function() {
    // the addition, which will check the value after a keyup (triggered by Ctrl+V)
    // We take the same regex as for allowedChars, but we add ^ after the first bracket : it means "all character BUT these"
    var forbiddenChars = new RegExp("[^0-9\-]", 'g');
    if (forbiddenChars.test($(this).val())) {
        $(this).val($(this).val().replace(forbiddenChars, ''));
    }
});

The result of what's happening at the moment is that if a character was entered such as "z" in #ecNumber , the validation regex code will fire and stop the character "z" appearing in the input - good. However, processPrimarySearch() will also fire because it's defined inside the .on for any input in the #primarySearch form.

What I want to do is run the validation regex inside my .on but only if it's the #ecNumber or #casNumber fields ( #substanceName must not be validated here). 我想做的是在.on内运行验证正则表达式,但.on是它是#ecNumber#casNumber字段( #substanceName不得在此处进行验证)。

I've managed to write the following which uses an array to say which field the user is entering input on. Where I'm doing the console.log is where I need the validation regex to occur

 $('#primarySearch input[type="text"]').on({
    "keyup": function(e) {
      // Ignore tab key
      if (e.which != 9) {

        var arr = ["ecNumber", "casNumber"];
        if ($.inArray($(this).attr('id'), arr)!== -1) {
            console.log($(this).attr('id'));
        }  

        processPrimarySearch.call(this);
      }
    }
});

What is the best way to do this? I'm unsure whether to move the code which does the regex into a function, and then call it (with .call ?) or some other method? And are there any issues with this being asynchronous in nature?

It's all about program flow and how you want to handle it. Your problem is not really an async problem in the last way that you presented your code. Here is one solution (of many possible ones). I put some comments in the code to explain the basics.

$('#primarySearch input[type="text"]').on({
    "keyup": function(e) {
        // if this is not the tab key and the input contains valid characters
        if (e.which != 9 && isThisValid($(this), e)) {
            processPrimarySearch.call(this);
        }
        else {
            e.preventDefault();
        }
    }
});


function isThisValid($elem, event) {
    var ids = ["ecNumber", "casNumber"], // ids to validate, everything else is valid
        result = true; // default result

    // is this one of the id's to validate?
    if(ids.indexOf($elem.attr('id')) !== -1) {
        // do some validation
        var allowedChars = new RegExp("^[0-9\-]+$"),
            str = String.fromCharCode(!event.charCode ? event.which : event.charCode);

        // is it valid?
        if (!allowedChars.test(str)) {
            result = false;
        }
    }

    return result;
}

function processPrimarySearch() {
    // ...    
}

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