在这个简短的教程中,它涵盖了在vuejs中验证输入表单type=url的一步步的教程。URL验证可以使用正则表达式模式来完成。
以下是创建一个应用程序的步骤顺序
-
首先,使用
vuecli工具创建一个Vue应用程序 -
通过发布以下命令确保vuecli npm命令已经安装。
B:\blog\jswork>vue --version @vue/cli 4.5.9这将给出已安装工具的版本号,如果没有安装,在终端运行以下命令
npm install -g @vue/cli这将把vuecli安装到你的机器上。
-
接下来,创建新的应用程序
vue create command,如下所示vue create vue-input-url -n这将创建vuejs应用程序--配置了文件、依赖关系和构建管道,并准备启动该应用程序
-
进入应用程序根目录,使用
npm run serve命令运行一个应用程序cd vue-input-url npm run serve这将启动应用程序并在浏览器中打开localhost:3000
输入类型的URL模式验证
输入表单是UI页面中的基本表单,用于接受用户的输入。
以下是一步一步的指南,使用以下方法为输入表单添加验证功能regular expression pattern
-
在
src/components文件夹下创建一个vuejs componentInputUrlComponent。VueJS组件包含以下标签下的html、javascript和样式
<template>
// html template code
</template>
<script>
// javascript code
</script>
<style>
// css styles
</style>
html模板包含UI元素逻辑,即显示给用户的视图层,这看起来像用户看到的页面。 javascript代码包含控制器逻辑,数据如何传递给/来自视图层 CSS样式 - 包含UI元素的样式
- 创建一个输入元素到视图层
<input type="url" placeholder="Website url" v-model="email" @input="change($event)"
@change="change($event)"/>
An input text box is displayed with type=url only
`v-model` is a vuejs directive to have a two-way data binding
`@input` and `@change` are two change handlers while the user typing the text.
输入文本框显示为type=url onlysv-model 是一个vuejs指令,用于双向数据绑定@input 和@change 是用户输入文本时的两个变化处理程序。
-
在vue组件的脚本中,添加以下内容
创建了三个实例成员url--用来保存表单的输入值isValid--存储输入类型的验证错误数据regex:是测试url验证的正则表达式
用于URL表单的正则表达式 同样的正则表达式也可以用于
javascript应用程序。regex=[-a-zA-Z0-9@:%_+.~#?&//=]{2,256}(.[a-z]{2,4})?\b(/[-a-zA-Z0-9@:%_+.~#?&//=]*)?在
methods部分,创建了两个方法,change - 处理模板中与@change event绑定的更改事件。isUrlValidfunction - 检查正则表达式。change:function(e){ const url = e.target.value this.isURLValid(url); }, isURLValid: function(inputUrl) { this.isValid= this.reg.test(inputUrl) } -
最后,使用
v-if指令属性显示错误。<div class="error" v-if="!isValid">URL is Invalid</div
下面是 InputUrlComponent 的完整源代码
<template>
<div class="hello">
<h3>Vuejs Input type url validation</h3>
<br />
<input type="url" placeholder="Website url" v-model="email" @input="change($event)"
@change="change($event)"/>
<div class="error" v-if="!isValid">URL is Invalid</div
</div>
</template>
<script>
export default {
name: "InputUrl",
data() {
return {
url: "",
isValid: false,
regex: [-a-zA-Z0-9@:%_+.~#?&//=]{2,256}(.[a-z]{2,4})?\b(/[-a-zA-Z0-9@:%_+.~#?&//=]*)?
};
},
methods: {
change:function(e){
const url = e.target.value
this.isURLValid(url);
},
isURLValid: function(inputUrl) {
this.isValid= this.regex.test(inputUrl)
}
}
};
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
h3 {
margin: 40px 0 0;
}
ul {
list-style-type: none;
padding: 0;
}
li {
display: inline-block;
margin: 0 10px;
}
a {
color: #42b983;
}
.error{
color:red;
}
</style>
输出:
