[关闭]
@bravf 2015-12-17T02:35:10.000000Z 字数 1947 阅读 1007

SmallValidator

未分类


import mode:

  1. //script link
  2. <script src="small-validator.js"></script>
  3. //commonjs
  4. var SmallValidator = require('small-validator.js')
  5. //amd
  6. define(['small-validator.js'], function (){
  7. })

sometimes, we have a user form like this:

  1. <form class="js-test-form">
  2. <input type="text" class="js-user"/>
  3. <input type="password" class="js-password">
  4. <button class="js-submit-btn">提交</button>
  5. </form>

we can valid the form with small-validator:

  1. var SmallValidator = require('small-validator.js')
  2. //create a form control
  3. var formControl = new SmallValidator.control()
  4. //create user control
  5. var userControl = SmallValidator.control('.js-user')
  6. // add user rules
  7. var notEmptyRule = SmallValidator.required('username is required')
  8. var lengthRule = SmallValidator.rule(/^*{5,8}$/, 'username length should in 5..8')
  9. var userExistsRule = SmallValidator.rule('userExists.php', function (control, data){
  10. if (data.exist){
  11. return false
  12. }
  13. else {
  14. return true
  15. }
  16. }, 'user already exist')
  17. userControl.add(notEmptyRule, lengthRule, userExistsRule)
  18. //create password control
  19. var passControl = SmallValidator.control('.js-password')
  20. //add password rules
  21. var notEmptyRule = SmallValidator.required('password is required')
  22. var lengthRule = SmallValidator.rule(function (control){
  23. var value = control.val()
  24. return /^\d{5,8}$/.test(value)
  25. }, 'password length should in 5..8 and all chars should be number')
  26. passControl.add(notEmptyRule, lengthRule)
  27. //add controls to form
  28. formControl.add(userControl, passControl)
  29. //bind event
  30. $('.js-submit-btn').on('click', function (){
  31. formControl.check().done(function (){
  32. //when valid ok
  33. })
  34. .fail(function (){
  35. //when valid fail
  36. })
  37. })

actually, a more simple method:

  1. var formControl
  2. with (SmallValidator){
  3. formControl = control().add(
  4. //user
  5. control('.js-user').add(
  6. required('user is required'),
  7. length([5, 8], 'username length should in 5..8'),
  8. rule('userExists.php', function (control, data){
  9. if (data.exist){
  10. return false
  11. }
  12. else {
  13. return true
  14. }
  15. }, 'user already exist')
  16. ),
  17. //password
  18. control('.js-password').add(
  19. required('password is required'),
  20. rule(/^\d{5,8}$/, 'password length should in 5..8 and all chars should be number')
  21. )
  22. )
  23. }

read soure code and enjoy it!

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注