JavaScript Email Validation with Regex

时间:2016-12-09 12:54:00

标签: javascript regex knockout.js

I am currently writing a binding handler in knockout to use the regular expression to validate the email. This is done using the RFC 2822 compliant regex.

I am trying to use RegExp('MY_REG_EXP')

MY_REG_EXP = [a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?

But since I am using single quotes (code quality purpose) at the beginning it is causing the binding handler not to validate the contents on update.

ko.bindingHandlers.emailInput = {
        init: function(element, valueAccessor, allBindingsAccessor, bindingContext) {
            ko.bindingHandlers.textInput.init(element, valueAccessor, allBindingsAccessor, bindingContext);
        },

        update: function(element, valueAccessor) {
            $(element).on('keydown', function (event) {
                if (event.keyCode === 32) {
                    event.preventDefault();
                }
            });

            var value = ko.unwrap(valueAccessor()),
                regex = new RegExp('^[a-z0-9!#$%&/\'*+/=?^_`{|}~-]+(?:\/.[a-z0-9!#$%&/\'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\/.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$');
            if (value.trim() !== '' && !regex.test(value)) {
                element.style.backgroundColor = '#EDB2B2';
            } else {
                element.style.backgroundColor = 'white';
            }
        }
    };

Any feedback on my approach is appreciated.

2 个答案:

答案 0 :(得分:1)

JavaScript regex email validation has been obsolete for half a decade at least.

<input type="email" />

Done.

答案 1 :(得分:0)

我已经使用/ \ escape字符修复了这个问题。单引号检查是我们构建过程的一部分,我不想不必要地做出异常。

ko.bindingHandlers.emailInput = {
        init: function(element, valueAccessor, allBindingsAccessor, bindingContext) {
            ko.bindingHandlers.textInput.init(element, valueAccessor, allBindingsAccessor, bindingContext);
        },

        update: function(element, valueAccessor) {
            var value = ko.unwrap(valueAccessor()),
                regex = new RegExp('[a-z0-9!#$%&/\'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&/\'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?');
            if (value.trim() !== '' && !regex.test(value)) {
                element.style.backgroundColor = '#EDB2B2';
            } else {
                element.style.backgroundColor = 'white';
            }
        }
    };