Giter Club home page Giter Club logo

jbvalidator's Introduction

HTML 5 & Bootstrap Jquery Form Validation Plugin

HTML 5 & Bootstrap 5 & Jquery 3

jbvalidator is a fresh new jQuery based form validation plugin that is created for the latest Bootstrap 5 framework and supports both client side and server-side validation.

  • Multiple languages.
  • Custom error messages.
  • Custom validation rules.
  • Easy to use via HTML data attribute.

Installation

npm i @emretulek/jbvalidator

Or grab from jsdelivr CDN :

<script src="https://cdn.jsdelivr.net/npm/@emretulek/jbvalidator"></script>
  • Html 5 validation
  • data-v-equal: id of the element that should be the same
  • data-v-min-select: multiple selectbox, minimum selectable count
  • data-v-max-select: multiple selectbox, maximum selectable count
  • data-checkbox-group: the parent attribute of group checkbox elements
  • data-v-min: alternative of the min attribute, this can be used for attribute type text
  • data-v-max: alternative of the max attribute, this can be used for attribute type text
  • data-v-min-length: alternative of the minlength attribute
  • data-v-max-length: alternative of the maxlength attribute
  • data-v-min-size: the input type file minimum file size (byte)
  • data-v-max-size: the input type file maximum file size (byte)
  • data-v-message: alternative error mesage

Methods

  • validator: add new custom validation
  • checkAll(formSelector = null, event = null): show errors without submitting the form, return error count
  • errorTrigger(inputSelector, message): show the error messages returned from the server.
  • reload(): reload instance after dynamic element is added

Usage

The form's attribute have to novalidate <form novalidate>

<script src="dist/jbvalidator.min.js"></script>
<script>
    $(function (){

        let validator = $('form.needs-validation').jbvalidator({
            errorMessage: true,
            successClass: true,
            language: "https://emretulek.github.io/jbvalidator/dist/lang/en.json"
        });

        //custom validate methode
        validator.validator.custom = function(el, event){
            if($(el).is('[name=password]') && $(el).val().length < 5){
                return 'Your password is too weak.';
            }
        }

        validator.validator.example = function(el, event){
            if($(el).is('[name=username]') && $(el).val().length < 3){
                return 'Your username is too short.';
            }
        }

        //check form without submit
        validator.checkAll(); //return error count

        //reload instance after dynamic element is added
        validator.reload();
    })
</script>

Serverside validation

You can show the error messages returned from the server. The ".errorTrigger" method can be used for this.

.errorTrigger(element, message)

<script src="dist/jbvalidator.min.js"></script>
<script>
    $(function (){

       let validatorServerSide = $('form.validatorServerSide').jbvalidator({
            errorMessage: true,
            successClass: false,
        });

        //serverside
        $(document).on('submit', '.validatorServerSide', function(){

            $.ajax({
                method:"get",
                url:"http://jsvalidation.test/test.json",
                data: $(this).serialize(),
                success: function (data){
                    if(data.status === 'error') {
                        validatorServerSide.errorTrigger($('[name=username]'), data.message);
                    }
                }
            })

            return false;
        });
    })
</script>

Options

{
    language: '', //json file url
    errorMessage: true,
    successClass: false,
    html5BrowserDefault: false,
    validFeedBackClass: 'valid-feedback',
    invalidFeedBackClass: 'invalid-feedback',
    validClass: 'is-valid',
    invalidClass: 'is-invalid'
}

Language file content

{
  "maxValue": "Value must be less than or equal to %s.",
  "minValue": "Value must be greater than or equal to %s.",
  "maxLength": "Please lengthen this text to %s characters or less (you are currently using %s characters).",
  "minLength": "Please lengthen this text to %s characters or more (you are currently using %s characters).",
  "minSelectOption": "Please select at least %s options.",
  "maxSelectOption": "Please select at most %s options.",
  "groupCheckBox": "Please select at least %s options.",
  "equal": "This field does not match with %s field.",
  "fileMinSize": "File size cannot be less than %s bytes.",
  "fileMaxSize": "File size cannot be more than %s bytes.",
  "number": "Please enter a number.",
  "HTML5": {
    "valueMissing": {
      "INPUT": {
        "default": "Please fill out this field.",
        "checkbox": "Please check this box.",
        "radio": "Please select one of these options.",
        "file": "Please select a file."
      },
      "SELECT": "Please select an item in the list."
    },
    "typeMismatch": {
      "email": "Please enter an e-mail address.",
      "url": "Please enter a URL."
    },
    "rangeUnderflow": {
      "date": "Value must be %s or later.",
      "month": "Value must be %s or later.",
      "week": "Value must be %s or later.",
      "time": "Value must be %s or later.",
      "datetimeLocale": "Value must be %s or later.",
      "number": "Value must be greater than or equal to %s.",
      "range": "Value must be greater than or equal to %s."
    },
    "rangeOverflow": {
      "date": "Value must be %s or earlier.",
      "month": "Value must be %s or earlier.",
      "week": "Value must be %s or earlier.",
      "time": "Value must be %s or earlier.",
      "datetimeLocale": "Value must be %s or earlier.",
      "number": "Value must be less than or equal to %s.",
      "range": "Value must be less than or equal to %s."
    },
    "stepMismatch": {
      "date": "You can only select every %s. day in the date calendar.",
      "month": "You can only select every %s. month in the date calendar.",
      "week": "You can only select every %s. week in the date calendar.",
      "time": "You can only select every %s. second in the time picker.",
      "datetimeLocale": "You can only select every %s. second in the time picker.",
      "number": "Please enter a valid value. Only %s and a multiple of %s.",
      "range": "Please enter a valid value. Only %s and a multiple of %s."
    },
    "tooLong": "Please lengthen this text to %s characters or less (you are currently using %s characters).",
    "tooShort": "Please lengthen this text to %s characters or more (you are currently using %s characters).",
    "patternMismatch": "Please match the request format. %s",
    "badInput": {
      "number": "Please enter a number."
    }
  }
}

jbvalidator's People

Contributors

ayurmedia avatar bredecl avatar emretulek avatar mibou avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

jbvalidator's Issues

data-v-equal hangs page

Hello,
I have a little problem with data-v-equal
I have 2 inputs - password and confirm and I want the second to be the same as the first (pretty standart, right...)...
When you type in the password and there is nothing in confirm there is no problem but if you have any text in confirm and then type something in password or change the password value the whole page hangs. Something it bounces back and 'wakes up' but it takes a ton of time. You can see the same behaviour in the demo page: https://emretulek.github.io/jbvalidator/
Try filling something in 'equal - rePassword' than start typing in password and it hangs at some point.

How can we display Custom Error message

//custom validate method
validator.validator.custom = function(el, event){ if($(el).is('[name=password]') && $(el).val().length < 5){ return 'Your password is too weak.'; } }
This method only return but it can not display any error on the screen.

Not Working On Dynamically Added Elements

Everything is good but If I am adding an element dynamically on the page, the pattern validation does not work, and also element is not available in the custom function.
Here is my code please review this.
let li = '<li class="list-group-item p-0 border-bottom-0" id="tiktok-li"> <div class="input-group social-account-inputs position-relative border-bottom"> <a href="javascript:;" class="input-group-text bg-transparent border-0 p-0"> <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 32 32" width="24px" height="24px"> <g id="surface74321354"> <path style=" stroke:none;fill-rule:nonzero;fill:rgb(80.000001%,80.000001%,80.000001%);fill-opacity:1;" d="M 4.769531 30.398438 C 3.019531 30.398438 1.601562 28.980469 1.601562 27.230469 L 1.601562 4.769531 C 1.601562 3.019531 3.019531 1.601562 4.769531 1.601562 L 27.230469 1.601562 C 28.980469 1.601562 30.398438 3.019531 30.398438 4.769531 L 30.398438 27.230469 C 30.398438 28.980469 28.980469 30.398438 27.230469 30.398438 Z M 26.59375 29.761719 C 28.339844 29.761719 29.761719 28.339844 29.761719 26.59375 L 29.761719 5.40625 C 29.761719 3.660156 28.339844 2.238281 26.59375 2.238281 L 5.40625 2.238281 C 3.660156 2.238281 2.238281 3.660156 2.238281 5.40625 L 2.238281 26.59375 C 2.238281 28.339844 3.660156 29.761719 5.40625 29.761719 Z M 26.59375 29.761719 "/> <path style=" stroke:none;fill-rule:nonzero;fill:rgb(0%,0%,0%);fill-opacity:1;" d="M 7.054688 0.601562 C 3.507812 0.601562 0.601562 3.507812 0.601562 7.054688 L 0.601562 24.945312 C 0.601562 28.492188 3.507812 31.398438 7.054688 31.398438 L 24.945312 31.398438 C 28.492188 31.398438 31.398438 28.492188 31.398438 24.945312 L 31.398438 7.054688 C 31.398438 3.507812 28.492188 0.601562 24.945312 0.601562 Z M 7.054688 3.398438 L 24.945312 3.398438 C 26.980469 3.398438 28.601562 5.019531 28.601562 7.054688 L 28.601562 24.945312 C 28.601562 26.980469 26.980469 28.601562 24.945312 28.601562 L 7.054688 28.601562 C 5.019531 28.601562 3.398438 26.980469 3.398438 24.945312 L 3.398438 7.054688 C 3.398438 5.019531 5.019531 3.398438 7.054688 3.398438 Z M 17.398438 6.199219 L 17.398438 20.199219 C 17.398438 21.761719 16.164062 23 14.601562 23 C 13.035156 23 11.800781 21.761719 11.800781 20.199219 C 11.800781 18.636719 13.035156 17.398438 14.601562 17.398438 L 14.601562 14.601562 C 11.523438 14.601562 9 17.125 9 20.199219 C 9 23.277344 11.523438 25.800781 14.601562 25.800781 C 17.675781 25.800781 20.199219 23.277344 20.199219 20.199219 L 20.199219 11.644531 C 21.359375 12.542969 22.734375 13.179688 24.296875 13.199219 L 24.339844 10.398438 C 22.035156 10.367188 20.199219 8.515625 20.199219 6.199219 Z M 17.398438 6.199219 "/> </g> </svg> </a> <input type="hidden" name="social_accounts[followers][]" value="" /> <input type="text" class="form-control common-social-input border-0 pe-2rem" pattern="^\S+$" data-pattern-message="i.e. johndoe" name="social_accounts[url][]" placeholder="username" id="tiktok" value="" required /> <input type="hidden" name="social_accounts[provider][]" value="tiktok"> <a href="javascript:;" class="position-absolute bg-transparent hide-show-icon-position remove-field" data-option-id="tiktok-li" style="z-index: 99;" ><i class='bx bx-x'></i></a> </div> </li>'; $(li).insertAfter('#select-li');

I use tick backs for li but it does not work on github so I change it to single qoutes.
validator.validator.custom = function(el, event) { if ($(el).is('[name="social_accounts[url][]"]')) { console.log($(el)); } }
this element does not appear in the console ever however if I add this element on page load it gets perfectly.
@emretulek @Mibou @bredecl please look into it

Problem with bootstrap-select

I face one problem with bootstrap-select and jbvalidator. When the two plugins are activated, the jbvalidator make the search box of bootstrap-select plugin not working.

Inked148751291-eae69911-9d9d-4400-b790-a8166e89f4f5_LI

Spanish translation

Hello,

I don't know how to contact with emretulek. I have attached the spanish translation.
es.zip

Great project!

Add data-v-different validation

I have a standard password change form. It has the following fields: Current Password, New Password and Confirm New Password.

I added data-v-equal="#new_password" to the Confirm Password field so typing in either of the two fields will trigger the not equal error when the two fields do not match. This works as it should.

I would like to have the opposite type of validation for the New Password field. An error should be triggered when it matches the Current Password field. I can do this with the following code but the error is triggered only by typing in the New Password field.
if ( $('[name=new_password]').val() === $('[name=current_password]').val() )
I'd like the error to be triggered when typing in either the Current Password or the New Password fields.

Hence my new feature request for data-v-different validation. How can I implement this functionality on my form if you do not feel this feature is necessary?

Vertical alignment icons inside input

I use Bootstrap 5 and jbvalidator (https://github.com/emretulek/jbvalidator).

I want to use icon inside input. Here is the code:

<div class="input-group mb-3"><i class="ci-user position-absolute top-50 translate-middle-y text-muted fs-base ms-3"></i>
    <input class="form-control rounded-start" type="text" placeholder="Username" required>
</div>

And here is result: https://i.stack.imgur.com/hRyUQ.jpg

if the validator marks it as incorrect, it moves the icon down because the vertical centering is set to 50%. Here is result: https://i.stack.imgur.com/IgC9q.jpg

I don't know how to elegantly center the icon vertically even if an error message is displayed.

Nice Library

Thanks for creating a great library, I am having a little trouble with an edge case.
I'm using the smart wizard library which breaks large forms into pages of a wizard
https://github.com/techlab/jquery-smartwizard

The problem I am facing is that the validation doesn't kick in until the last page of the wizard when the form is submitted, or if I interact with the form elements.

So my question to you is how would I manually invoke the validation routine?

Thanks in advance.

Issue on checkbox validation using checkAll() method

@emretulek please look into it.
when I call to checkAll() method manually then I receive this error.
jbvalidator.js:303 Uncaught TypeError: Cannot read properties of undefined (reading 'originalEvent')
at Function.groupCheckBox (jbvalidator.js:303)
at jbvalidator.js:192
at Array.map ()
at validationRun (jbvalidator.js:190)
at HTMLInputElement. (jbvalidator.js:127)
at Function.each (jquery.min.js:2)
at S.fn.init.each (jquery.min.js:2)
at Object.checkAll (jbvalidator.js:126)
at HTMLFormElement. (286:1826)
at HTMLFormElement.dispatch (jquery.min.js:2)
Screenshot from 2021-11-15 13-12-19
Screenshot from 2021-11-15 13-13-02

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.