Vue.js中的一个简单函数是什么,我可以用来验证输入的格式?

时间:2017-07-17 08:02:10

标签: javascript validation vue.js

在Vue.js中我有这个:

<template>
    <button @click="sendMail(); $emit('close')">Send</button>
</template>
<script>
    methods: {
        sendMail () {
            axios.post('/mail', {email: this.email});
            this.$notify.make('Sent!', 'success');
        },
        invalidEmail () {
            this.$notify.make('Invalid email format!', 'failure'):
        }
    }
</script>

当电子邮件输入格式不正确时,我如何能够触发invalidEmail()

1 个答案:

答案 0 :(得分:2)

您可以使用正则表达式检查电子邮件的有效性。

正则表达式的来源:http://emailregex.com/

<template>
    <button @click="sendMail(); $emit('close')">Send</button>
</template>
<script>
    // Here is the regex to test if an email is valid
    const mailRegex = /^(([^<>()[\]\\.,;:\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,}))$/;
    module.exports = {
        // [...]
        methods: {
            sendMail () {
                // If this.email is not a valid email, abort by return and call this.invalidEmail
                if (!mailRegex.test(this.email)) return this.invalidEmail();

                axios.post('/mail', {email: this.email});
                this.$notify.make('Sent!', 'success');
            },
            invalidEmail () {
                this.$notify.make('Invalid email format!', 'failure'):
            }
        }
    }
</script>