开发者

Combine two regex

I'm using jquery.validationengine.en.js to (custom )validate my form fields. For one field, I'm using two custom validation. I don't want to display both the validation message for a field. It should display only one msg at a time. How to do that?

Please find the code below Note: allzero is used by some other fields too.

   "phone":   {
                  "regex": /^[0-9]{8,15}$/,
                  "alertText": "* Invalid phone number"
              },
   "allzero": {
                  "regex": /([^((\+)*(0*))])/,
                  "alertText": "* Invalid number"
              },

HTML code:

<input type="text" name="phone" id="phone" class="textBox textNormal validate[maxSize[30],custom[onlyNumberSp],custom[phonenumber],custom[allzero]]" onfocus="jQuery('#adduserform').validationEngine('attach',{Overflown:false})">

    <input type="text" name="mobile" id="mobile" class="textBox textNormal validate[maxSize[30],custom[onlyNumberSp开发者_StackOverflow社区],custom[mobile],custom[allzero]]" value="" onfocus="jQuery('#adduserform').validationEngine('attach',{Overflown:false})">


One way would be to always require a non-zero digit somewhere in the string. This can be done by the regex part [0-9]*[1-9][0-9]*. However, you then lose the ability to easily check the string length. This can be overcome by a lookahead assertion resulting in the following regex:

/^(?=[0-9]{8,15}$)[0-9]*[1-9][0-9]*$/


Looking at the validation engine usage instructions (at https://github.com/posabsolute/jQuery-Validation-Engine), it seems it's possible to validate a field using a custom function call (the funcCall validator). So, you should be able to use a function to check both regexps one after another, and return the appropriate error message if one of them doesn't match:

function checkPhoneNumber(field, rules, i, options){
    if (!field.val().match(/^[0-9]{8,15}$/))
        return "* Invalid phone number";
    else if (!field.val().match(/([^((\+)*(0*))])/))
        return "* Invalid number";
}


Here is how I could do it when using a function:

        "phoneORallzero": { 
            "func": function(field, rules, i, options){
                if (field.val().match(/^[0-9]{8,15}$/))
                    return true;
                else if (field.val().match(/([^((\+)*(0*))])/))
                    return true;
            },
            "alertText": "* invalid phone or number."
        }

In the HTML code:

... class = "validate[custom[phoneORallzero]]" ...
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜