如何使用ng-pattern验证特定的电子邮件地址?

时间:2017-05-09 15:35:34

标签: javascript angularjs regex ng-pattern

我的电子邮件验证具有特定格式ab123c@email.comab1234@email.com,其验证前5个字符,但不是使用angularjs ng-pattern的完整电子邮件地址。如何使用angularjs验证特定的电子邮件地址?

main.html中

<div layout="row">
    <md-input-container flex="100">
        <label>Cc</label>
        <input type="email" name="email" ng-model="notifyCtrl.cc" ng-list="," ng-pattern="pattern(user.type)">
        <div class="help-block" ng-messages="notifyForm.email.$error" ng-show="notifyForm.email.$touched && notifyForm.email.$invalid">
            <div ng-if="user.type === 'notify'">
                <div ng-message="pattern">
                    An email name must only contain a-z, A-Z, 0-9, or _ characters.(ie. ab123c@tad.com, ab1234@tad.com
                </div>
            </div>
        </div>
    </md-input-container>
</div>

ctrl.js

var emailFormat = new RegExp('^[a-z]{2}[0-9]{3}[a-z0-9]$'); 

$scope.pattern = function(type){ 
    if(type === 'notify') {
        return emailFormat; 
    }  
};

2 个答案:

答案 0 :(得分:0)

在输入电子邮件中,您可以使用以下ng-pattern

ng-pattern="/^[_a-z0-9]+(\.[_a-z0-9]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$/"

答案 1 :(得分:0)

这是检查有效电子邮件地址的最佳模式:

ng-pattern='/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/'

您可以尝试另一个正则表达式:

ng-pattern='/^(?!(?:(?:\\x22?\\x5C[\\x00-\\x7E]\\x22?)|(?:\\x22?[^\\x5C\\x22]\\x22?)){255,})(?!(?:(?:\\x22?\\x5C[\\x00-\\x7E]\\x22?)|(?:\\x22?[^\\x5C\\x22]\\x22?)){65,}@)(?:(?:[\\x21\\x23-\\x27\\x2A\\x2B\\x2D\\x2F-\\x39\\x3D\\x3F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