Vue Quickly implements universal form verification

This article opened the first sentence, I want to quote a word in Lu Xun’s “blessing”, that is: “I am stupid, really, I only know that the rear end is crud, I didn’t Think of the front end is form form all day “. Where is this sentence to talk? Probably, from the “full stack engineer” in the last half month. On the project, you need to make a city load function, as the name suggestions, is to complete the load on the map through the box selection and drag and drop. The blogger chose the way the front and rear ends are separated. It is found in this process: First, as long as there is a component that relies on jQuery, such as Kendoui, even if Vue is used, it still needs to operate DOM through jQuery. Secondly, there is only a DOM generated by Rozar, such as HTMLHELPER, VUE’s two-way binding suddenly becomes embarrassed, not to mention, @ 语 法 in Rozar and the @ 指 指 指 指 问题 问题 问题 问题 问题 问题-force generation list, because HTMLHELPER is used, suddenly suddenly get tireless, although the Rozar syntax is very powerful, I still don’t have the enthusiasm of C # in JavaScript, because it is too painful orz …

So, I want to do the front and rear end separation. First, I need to separate a set of front-end component libraries. If you don’t do this, you can’t talk about it, just like our company’s project, even if the frame is switched to .NET Core However, in a long period of time, we still write MVC because all components are the form of HTMLHELPER / TAGHELPER provided by the backend. I do this, in the process of doing a project, in fact, a part of the component is achieved through jQuery. Because of this, it is very easy to implement when it is not separated in the front and rear end. After the front and rear ends are separated, they have found a lot of things, such as the simplest. Form verification function, even if you are doing a new project, in order to ensure the consistency of the product, you still have to rely on the old project, so this blog mainly wants to say how the front and rear ends, how is the Vue era? Go to do the verification of the form. Because I don’t want to test my colleagues and give me bug, ask me why I only have verification from the backend interface, and there is no verification from the front-end page. I hope, before writing this blog, IYou can achieve exactly the same old projects and form validation. As CRUD is to the back-end, 80% of the front end is writing Form form, so this thing is quite interesting.

The simplest form validation

OK, As the front-end frame closest “to gas”, Vue document can be quite the “people” it! Why do I say, because in fact in the official documents, particularly great example has been provided a form validation, this example reminds me of the scene when a bank to do automated tools, because both are based on the idea MVVM, so , it is very easy to understand, and that is: by storing a list of error messages, and this error message is bound to the view layer, so the verification process is actually add to this list the error message in the process. Together we look at this example:

  

Hello, please log in

0 ">
{ {errorList.join ( ';')}}
var vm = new Vue ({el: '#loginFrom', data: {email: "" , password: "", errorList: []}, methods: {validate: function () {THIS.ERRORLIST = [] IF (this.email == '') {this.errorlist.push ('Please enter the mailbox');} else {var rag = / ^ ([A-ZA-Z] | [0- 9]) (\ w | \ -) ​​+ @ [a-za-z0-9] + \. ([A-ZA-Z] {2, 4}) $ /; if (! Reg.test (this. Email) {this.errorList.push ('Please enter a valid email');}}}} f (this.password == ') {this.errorlist.push (' Please enter your password ');} else {ix "< 6) { this.errorList.push('密码长度不得少于6位'); } } return this.errorList.length <= 0; }, login: function () { if (this.validate()) { alert('登录成功'); } } } }); In order to exclude the influence of unrelated content to everyone, when writing this example, bloggers exclude all complex HTML structures and CSS styles. After simple moiste, the effect of this example is shown below. Sure enough, the GUI satisfies the side of people’s control, which allows this world to run the CLI, bootstrap is the favorite of this “full stack engineer” of the blogger. This verification method is simply a human instinct reaction, but this happens to be the worst example, because this code is completely impossible, you can imagine it, if you continue to increase your password strength, such as uppercase, numbers, etc. Verify that this code will make something like, so this is the simplest form verification, the same, the worst form verification.

Based on jQuery form Verification

Vue快速实现通用表单验证功能

In fact, if it is not because old projects rely on jQuery, and new projects need to be consistent with old projects in some places, who will use jQuery in the world of VueWoolen cloth? Because data-driven and event-driven, really are two different ideas, because I have seen an event not to listen and spend a whole day people …… So, here using jQuery form validation plug-in jQuery Validation, purpose There is only one blogger to realize their promise and do a project exactly the same old form validation. Official this example the biggest problem is that it’s a logical extension of the test is relatively poor, the back-end students should have experience on this matter, such as the actual business often have a mailbox, phone number, non-empty, numbers, and so on regular validation rules , the rear end often Attribute-based authentication or such libraries FluentValidation, therefore, the core problem is, can define appropriate validation rule. Next, we implement validation plugin jQuery form validation.

Typically, jQuery Validation support for controls and codes for the two kinds of authentication. The so-called control-oriented, refers to add similar in the control where required

,

email

,

range and so extended attributes, jQuery Validation Built-in validation dozen standard rules, could meet our daily use. And for code validation rules that are defined by JavaScript, which is consistent with data-driven style Vue, because everything is in the JavaScript objects, and these objects can be used as data in the Vue. Naturally, on the basis of the first example, we can very easily be extended based on the verification jQuery form: var vm = new Vue ({el: ‘ #loginFrom ‘, data: {email: “”, password: “”, validators: {rules: {email: {required: true, email: true}, Password: {Required: True, minLENGTH: 6,}}, Messages: {email: {required: “Please enter the mailbox”, email: “Please enter a valid email”}, password: {required: “Please enter the password “, MINLENGTH:” The password is not less than 6 “}}}}, mounted: function () {$ (‘# loginfrom’). Validate (this.validators);}});

  For current form loginfrom, its verification rules are Validators, which fully refer to the API documentation of  jQuery Validation 
, and details can be from jQuery validation
Let’s learn more. The only thing that looks uncomfortable here is

#loginfrom , because it looks at the entire Vue. However, like the current project of the blogger, if the old project uses jQuery to verify the form, use the new project developed by VUE to be compatible with the design style of the old project, what can I use jQuery? ? Have to say, Vue acts as a progressive development framework, truly takes care of the front-end engineers of each "age" section. The form verification effect after jQuery validation is as follows: through

jQuery validation

We may feel a little different, that is, the form is actually quite interesting. Maybe because I was originally a boring person, so I felt interesting at a new thing. Just like I have a check in the backend while submitting data, it can be sacrificed is actually the experience of the entire front end. And if the data is verified on the front end, the verification is in the input process or the input completed check is the submission function of the form or it initiates an AJAX request, which is indeed a lot of details. . The first solution does not support remote checks, which makes it possible to explain that the check itself is not only the front end, the same, with the front-end check, does not mean that the rear end can not be verified. The front time is in knowing about questioning, and most is that the front end should not completely trust the data returned by the backend, strictly, we should not trust the data provided by anyone, and this is the meaning of the verification of this thing itself. Vue快速实现通用表单验证功能

Based on Vue-based form verification

OK, if the two checks in front are because we have a little historical burden, then, then, we will try to adopt More “modern” form verification method. Through the content of the data check this section, we understand the officially recommended two form validation plugins are Vuelidate and VeeValidate, and the first example in this blog is actually evolved by the examples in the document. Come. I personally prefer the latter, so we will use this plugin to complete the third example. First, we create a Vue project through Vue-CLI , then install the following

VEE-VALIDATE

and Vue-I18N two plugins: NPM Install Vee-Validate@2.0.0 –savenpm Install Vue-I18N

Note that the version number is specified here, this is Because the latest 3.x is beyond my newcomer’s acceptance range, one sentence is too difficult! Next, we are in the entrance document
 MAdd the following code to enable these two plugins:   
Import Vuei18n from ‘Vue-I18n’; import Veevalidate from ‘Vee- Validate ‘; import zh_cn from’ VEE-VALIDATE / DIST / LOCALE / EN_CN ‘// Enable Vue International Plugin Vue.use (Vuei18N) // Configure VeeValidateConst I18N = New Vuei18N ({locale:’ zh_cn ‘,}) Vue. Use (veevalidate, {i18n, i18nrootkey: ‘validation’, Dictionary: {zh_cn}});

Next, write a single file component

Loginform.Vue
   
Hello, please log in

{RRORS.FIRST (’email’)}}
   Password  

{RRORS.First ('password')}}

Remember Password

login

export default {name: "LoginForm", components: {}, data: () => ({email: "", password: ""}), methods: {login: function () {}}}; .login {color: white; height: 38px; width: 300px; background-color: # 2b669a;}
v-validate
and
data-vv-as these two properties. For example, we here need to validate the mailbox entered by the user is legitimate, whether the mailbox is empty, then we can use the following syntax:
{{errors .first ( 'email')}}
the instruction syntax is referred to in the Vue, and

data-vv-as is is a characteristic in HTML5 for prompt information to an alias fields. In fact, this plugin also built a number of common validation rules. When the value in the control does not satisfy the verification condition, it will be in the errors Error message in 123, so we decide whether or not to display the error message based on the false message, this is the role of this plugin. Run this example, we will get the following results.

Since mentioned the most difficult place to verify this type of form is extension, then let’s take a look at how to expand a new check rule, here is the most common The mobile phone number check is an example. The individual thinks this is the most powerful place in this plugin:
   Validator.extend ('ismobile', {Messages: {zh_cn: Field => Field + 'must be 11-bit mobile number'}, validate: value => {return value.length === 11 && / ^ ((13 | 14 | 15 | 17 | 18) [0-9] {1} \ D {8}} $ /. Test (value)}}) 

I believe that through today's blog, everyone should have a little experience in the form of form in Vue. This type of verified library or framework is actually very much. Integrating the work you want to do in Vue, there is no plugin, and verify when the control triggers related events or forms commit. As a newcomer of Vue, this process can be described as a long way. You probably not think of, I am working hard to finish these examples at the early morning, I have finished doing these examples, and the class in the past two or three months has been more than I have been more than three years. Is this a good thing or a bad thing? ? Sometimes I don't know if I can still stick to it. The past is already awkward, people will inevitably feel confused!
This article is summarized

This blog mainly shares the realization of Vue below the list of Vue, and prompted the original motivation to study all this. It is the new project that is stem from a practical work through Vue. Do not separate the front and backs, do you want to use jQuery in the project, which should not be used frequently, this is actually unrelated to three pieces.Thing, and this is what 90% of people simply do not care, just to have a look quite "adult" approach, the first thing is not the time to tangle who is at fault, but what can not be resolved immediately as well as how long it takes to solve the problem. It looks like no problem at all, may not care about the event itself right or wrong person, because he does not need to deal with these issues, stakeholders and relevant responsibilities are completely different, because you can not find a problem all procedures members here, this project is not yet a human programmer. I care about these unimportant matter, simply because I have a feeling for what they do, I just want to do it, I wish I was a pure person, and may have been purely down, good night! of the These are the Vue small series to introduce the rapid implementation of general form validation, we want to help, if you have any questions please give me a message, Xiao Bian will promptly reply to everyone. Thank you very much for your support of Tumi Cloud Website! If you think this article helps you, welcome to reprint, please indicate the source, thank you!

© Copyright Notice
THE END
Just support it if you like
like0
share
comment Grab the couch

Please log in to comment