jQuery Validation plugin custom method using regex

前端 未结 2 1854
生来不讨喜
生来不讨喜 2021-01-28 17:40

I need to make a new method for jQuery Validator and don\'t know where to start.

I would like it check that the email entered includes: \'@specificdomain.com\'.

相关标签:
2条回答
  • 2021-01-28 18:10
    var s="abc@specificdomain.com";  OR  var s=value;
    var split = s.split('@');
    var regex = /^([a-zA-Z0-9_.+-])/;
    var s2="@specificdomain.com";
    
    if(regex.test(split[0]) &&  s2 == split[1])
    
           return true;
    else
             return false;
    
    0 讨论(0)
  • 2021-01-28 18:14

    The following worked for me:

    jQuery.validator.addMethod('matchDomain', function(value, element) {
            var s=value;
            var split = s.split('@');
            var regex = /^([a-zA-Z0-9_.+-])+$/;
            **var s2="allcoles.com";**                  //The split array is the domain excluding the @
            **var optionalValue = this.optional(element);** //This is how other methods in alternativeMethods.js Validator handle this.
    
            **//Debugging - This is useful to see visually what is happening
            //alert(split[0]);  // Shows the inputted username i.e chris or smokey
            //alert(split[1]);  // Shows the inputted domain
            //alert(regex.test(split[0]));  //Shows unfilled inputs problem or bad characters, true if good, false if bad
            //alert(s2 == split[1]);**  // Shows if the inputted domain matches variable s2, if it does we get a true
    
            if (optionalValue) {
                return optionalValue;
                }
            **if(regex.test(split[0]) && (s2 == split[1]))**  // has to be == not equals
                {
                return true;
                }
            else
                {
                return false;
                }
            }, 'Please specify a @allcoles.com email');
    
    0 讨论(0)
提交回复
热议问题