vue-m-validator

1.1.4 • Public • Published

vue-m-validator

NPM version NPM monthly downloads NPM total downloads

Data Validation Library, for VueJs. Perhaps useful for other libraries/frameworks and other projects, but i created this library and using with VueJs with reactive data.

Example with form

Installation

npm install --save vue-m-validator

or

npm i -S vue-m-validator

Update package

npm update vue-m-validator

Use case

example with components

  • Required the library to your project
import validator from 'vue-m-validator';
  • Make library is reactive
data () {
    return {
      isFirstRun: true,
      username: '',
      email: '',
      password: '',
      password2: '',
      validator: validator
    };
}
  • If you use many forms on page in a different components, write the hook
  created () {
    validator.reset();
  }
  • And validate a form
  validator
    .addRule(RULE_1)
    .addRule(RULE_2)
    .addRule(RULE_N);

for the 'addRule' method, you should use as an argument the object that should have the following look:

  validator.addRule({
    expression: !USERNAME || USERNAME === ' ',
    name: 'username',
    msg: 'username field required'
  });
  • To manually add an error, use the 'addError'
  validator.addError({
    expression: false,
    name: 'test',
    msg: 'FatAl err0r'
  });
  • To manually remove the error, use the 'deleteError'
  validator.deleteError({
    name: 'test',
    msg: 'FatAl err0r'
  });
  • To manually delete all messages united by the same name, use the 'deleteAllErrorByName'
  validator.deleteAllErrorByName('test');
  • To perform server-side validation, try the following (additional in 1.1.0 version):
validator
  .addRule(RULE_1)
  .serverCheck({
    address: 'http://server/validation',
    method: 'POST',
    data: {
      name: 'test', // required parameter
      myKey: _mail
      // myKey - you can call it
      // anything and add more data,
      // for your own purposes
    },
    success: (responce) => {
      // in fact, in this callback function,
      // you can write anything. This is just an example.
      responce = JSON.parse(responce);
      if (!responce.status) {
        if (responce.errors.length === 0) {
          validator.addError({
            expression: false,
            name: 'test',
            msg: 'Unknown server error. Sorry Bro...'
          });
        } else {
          responce.errors.forEach((item, i, arr) => {
            validator.addError({
              expression: false,
              name: 'test',
              msg: item
            });
          });
        }
      } else {
        // after client verification and server-side
        // verification, if the status is returned
        // 'true', we can delete all error messages with
        // the 'name' property specified in the data to
        // be transmitted to the server.
        validator.deleteAllErrorByName('test');
      }
    },
    error: (responce) => {
      console.log('Server Error', responce);
    }
  });

see example

When I was making an example, I used such a php code on the server side (just an example):

  <?php
    Route::post("/validation",function(){
      header("Access-Control-Allow-Origin: *");
      header("Content-type: application/json");
      $response = [];
      $errors = [];
 
      if($_POST["myKey"] === ""){
        $response["status"] = false;
        $errors[] = "FROM SERVER error 0";
      }
 
      if($_POST["myKey"] !== "hello world"){
        $response["status"] = false;
        $errors[] = "FROM SERVER error 1";
      }
      if(count($errors)==0){
        $response["status"] = true;
      }
 
      $response["name"] = $_POST["name"];
      $response["errors"] = $errors;
 
      echo json_encode($response);
    });
 
  ?>

see example

  • In a templates you should use v-model for data and validate form data with functions
<input
    type="text"
    v-model="username"
    @blur="checkUsername(username)">
<button
    @click="register">Registration</button>
  • For showing all validation errors you can access the library object property 'errors'
<ul class="form-group">
  <li
    v-for="error in validator.errors">
      <small
        class="form-text text-muted"
        v-for="msg in error.msgs">
          {{msg}}
      </small>
  </li>
</ul>
  • To display one group message, use method 'getErrors(name)'
<ul v-if="isUsernameErrors">
  <li
    class="form-text text-danger"
    v-for="error in validator.getErrors('username')">
      &nbsp;{{ error }}
  </li>
</ul>

Readme

Keywords

Package Sidebar

Install

npm i vue-m-validator

Weekly Downloads

11

Version

1.1.4

License

MIT

Unpacked Size

51.8 kB

Total Files

11

Last publish

Collaborators

  • silksofthesoul