当前位置: 动力学知识库 > 问答 > 编程问答 >

javascript - Regular Expression in a single function

问题描述:

I have done some regular expression validation, here is the below what i did,

Javascript:

function fn1() {

var var1=/^(\s*|\d+)$/

if (document.myform.inp1.value.search(var1)==-1) {

alert("validation for digits failed")

}

}

function fn2() {

var var2=/^(?:\d+(?:,\d+)*(?:\.\d{2})?|\d+(?:\.\d{3})*(?:,\d{2})?)$/

if (document.myform.inp2.value.search(var2)==-1) {

alert("validation for currency failed")

}

}

function fn3() {

var var3=/^(0[1-9]|[12][0-9]|3[01])[- /.](0[1-9]|1[012])[- /.](19|20)\d\d$/

if (document.myform.inp3.value.search(var3)==-1) {

alert("validation for date failed")

}

}

</script>

Below is my HTML,

<form name="myform">

<div id="div1">

<input type="text" name="inp1" />

<input type="button" onClick="fn1()" value="chk1"/>

</div>

<div id="div2">

<input type="text" name="inp2" />

<input type="button" onClick="fn2()" value="chk2" />

</div>

<div id="div3">

<input type="text" name="inp3" />

<input type="button" onClick="fn3()" value="chk3" />

</div>

</form>

Now i need to combine all this into a single function which should accept the regular expression as a parameter. so there should be one JavaScript function which accepts three arguments (<<selector for input field>>, <<regular Expression>>, <<Error message>>). Please help how to achieve this.

网友答案:
function expression(selector, regex, error) {
    if (selector.value.search(regex)==-1) {
        alert(error);
    }
}

selector would have to be something along the lines of document.myform.inp1

网友答案:

You can do it like this;

function checkItem(elem, regex, errMsg) {
    if (elem.value.search(regex) == -1) {
        alert(errMsg);
    }
}

Example:

checkItem(document.myform.inp1, /^(\s*|\d+)$/, "validation for digits failed");
网友答案:

First put your validation functions into an object:

var validationFunctions = {
    digits: function (val) {
        ... fn1 here ...
    },
    currency: function (val) {
        ... fn2 here ...
    },
    date: function (val) {
        ... fn3 here ...
    }
};

Then your generic function would look something like this:

var validate = function (elementID, type) {
    var value = document.getElementById(elementID).value;

    return validationFunctions[type](value);
};

You'd call it like this:

validate('inputBoxID', 'digits');
validate('inputBoxID', 'currency');
validate('inputBoxID', 'date');
分享给朋友:
您可能感兴趣的文章:
随机阅读: