Giter Club home page Giter Club logo

angular-validation's Introduction

angular-validation 1.4.5

NPM version Build Status Code Climate Coverage Status devDependency Status

Client-side Validation should be simple and clean.
Don't let Client-side Validation dirty your controller.

Setup your Validation on config phase by using some rules (example)
If you prefer schema over html attributes , try angular-validation-schema (Demo)
And add Validation in your view only.

angularjs 1.2.x support to version angular-validation 1.2.x
angularjs 1.3.x support after version angular-validation 1.3.x
angularjs 1.4.x support after version angular-validation 1.4.x

Requirement

AngularJS 1.2.x (for angular-validation 1.2.x)
AngularJS 1.3.x (for angular-validation 1.3.x)
AngularJS 1.4.x (for angular-validation 1.4.x)

DEMO

http://hueitan.github.io/angular-validation/

Install

Install with npm

npm install angular-validation

or with bower

bower install angular-validation

Using angular-validation

<script src="dist/angular-validation.js"></script>
<script src="dist/angular-validation-rule.js"></script>
angular.module('yourApp', ['validation']);

// OR including your validation rule
angular.module('yourApp', ['validation', 'validation.rule']);

Writing your First Code

<form name="Form">
    <div class="row">
        <div>
            <label>Required</label>
            <input type="text" name="required" ng-model="form.required" validator="required">
        </div>
        <div>
            <label>Url</label>
            <input type="text" name="url" ng-model="form.url" validator="required, url">
        </div>
        <button validation-submit="Form" ng-click="next()">Submit</button>
        <button validation-reset="Form">Reset</button>
    </div>
</form>

Documentation API

Built-in validation in angular-validation-rule

  1. Required
  2. Url
  3. Email
  4. Number
  5. Min length
  6. Max length

5 and 6 require you to pass an inline parameter to set the length limit. Eg, maxlength=6.

Anyone can give a PR for this angular-validation for more built-in validation

Integrating with Twitter Bootstrap

To integrate this package with Bootstrap you should do the following.

Add the following LESS to your project

.ng-invalid.ng-dirty{
    .has-error .form-control;
}

label.has-error.control-label {
    .has-error .control-label;
}

Change the Error HTML to something like:

$validationProvider.setErrorHTML(function (msg) {
       return  "<label class=\"control-label has-error\">" + msg + "</label>";
});

You can add the bootstrap class .has-success in a similar fashion.

To toggle .has-error class on bootstrap .form-group wrapper for labels and controls, add:

angular.extend($validationProvider, {
    validCallback: function (element){
        $(element).parents('.form-group:first').removeClass('has-error');
    },
    invalidCallback: function (element) {
        $(element).parents('.form-group:first').addClass('has-error');
    }
});

License

MIT

CHANGELOG

See release

CONTRIBUTORS

Thank you for your contribution @lvarayut and @Nazanin1369 ❤️
Thanks for all contributors

angular-validation's People

Contributors

a15n avatar akolodeev avatar arthurhenning avatar austinpray avatar chorsnell avatar ctjhoa-linagora avatar dizlexik avatar dmitry-dedukhin avatar dvelopment avatar erictonussi avatar eyupatis avatar hueitan avatar huguangju avatar hung-doan avatar imgarylai avatar imranamans avatar liorcode avatar lopsided avatar lvarayut avatar musahaidari avatar nazanin1369 avatar nmccready avatar null-none avatar scottadamsmith avatar tb avatar thetutlage avatar think2011 avatar tylergraf avatar zack9433 avatar zvaraondrej 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  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  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

angular-validation's Issues

Reg Group validation

Group validation is not possible with this plugin? Or you have any idea to implement this?

Could you tell me the way to validate form when the input is clean.

Could you tell me the way to validate form when the input is clean.
I have a model $scope.form and it is empty object.
Now, I want to auto show validate message at initial screen.

Example: Althought user has not interacted with the form, but it show the message error
selection_007

(Refactor) Setup a new Validation

the original

// your module
angular.module('yourApp', ['validation'])
    .config(['$validationProvider', function ($validationProvider) {
        // Setup `ip` validation
        var expression = {
            ip: /^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/
        };

        var validMsg = {
            ip: {
                error: 'This isn\'t ip address',
                success: 'It\'s ip'
            }
        };

        validationProvider.setExpression(expression); // set expression
        validationProvider.setDefaultMsg(validMsg); // set valid message

        // Setup `huei` validation
        validationProvider.setExpression({

            /**
            * @param value , user input
            * @returns {boolean} true iff valid
            */
            huei: function (value) {
                return value === 'Huei Tan';
                // or you can do
                return $q.all([obj]).then(function () {
                // ...
                    return true;
                })
            }
        });

        validationProvider.setDefaultMsg({
            huei: {
                error: 'This should be Huei Tan',
                success: 'Thanks!'
            }
        });
    }]);

Need a better structure

reference: https://github.com/kelp404/angular-validator#register

is it a bug or somehow issue?

angular-validation 1.2.2

In my project, angular-validation is used as a git submodule. Somehow i got the error as follow:

Failed to instantiate module validation.rule due to:
TypeError: Cannot read property 'setDefaultMsg' of undefined
    at http://192.168.1.105:3000/assets/angular-validation/dist/angular-validation-rule.js?body=1:34:62
    at Object.d [as invoke] (http://192.168.1.105:3000/assets/angular/angular.min.js?body=1:35:265)
    at http://192.168.1.105:3000/assets/angular/angular.min.js?body=1:34:128
    at Array.forEach (native)
    at q (http://192.168.1.105:3000/assets/angular/angular.min.js?body=1:8:298)
    at e (http://192.168.1.105:3000/assets/angular/angular.min.js?body=1:33:445)
    at http://192.168.1.105:3000/assets/angular/angular.min.js?body=1:34:18
    at Array.forEach (native)
    at q (http://192.168.1.105:3000/assets/angular/angular.min.js?body=1:8:298)
    at e (http://192.168.1.105:3000/assets/angular/angular.min.js?body=1:33:445

is it a bug?

Server-side validation

Most common case and well understood example is the unique email validation during a user registration (JSON-Api).

Can you add an example on how to implement this in angular-validation.

ng-repeat with checkboxes

Hi,

I have a checkbox inside an ng-repeat like so:

<div class="checkbox" ng-repeat="item in vm.dataPoints">
    <label>
        <input type="checkbox"
                   checklist-model="vm.selectedDataPoints"
                   checklist-value="item.name"/>{{item.name}}
     </label>
 </div>

I want at least one checkbox to be checked, any idea on how I would go about this?

Thanks.

Try to including dependency but fail

install by rails bower, and then require in application

= reuqire angular-validation/dist/angular-validation

= reuqire angular-validation/dist/angular-validation-rule

requiring is successful, but when trying to include dependency

angular
.module("myApp", ["ngRoute", "validation", "validation.rule"])

It shows:

Uncaught Error: [$injector:modulerr] Failed to instantiate module myApp due to:
Error: [$injector:modulerr] Failed to instantiate module validation due to:
Error: [$injector:nomod] Module 'validation' is not available! You either misspelled the module name or forgot to load it. If registering a module ensure that you specify the dependencies as the second argument.

quite sure the installation was done. Don't konw what happened. Please help me! Very appreciate

Validate within Directive with ng-form

Is it possible to validate fields (type= select and input=text) within a directive which contains an ng-form?
At present they are not triggering on page submit but work when switching between a selection and default state.

<ng-form name="innerForm">
    <select ng-change="selectChange(field, items)" name="dropdown" ng-model="field" class="form-control" ng-options="item.id as item.value for item in items"  validator="required">
       <option value="">{{intValue}}</option>
    </select>
</ng-form>

Thanks for any help.

Gav

How to pass multiple values into the function?

Hi,
Below is my validation function for range

$validationProvider.setExpression({
    range: function (value, min, max) {
        if (value > min && value < max) {
            return value;
        }
    }
});

May i know how to pass in the min and max values into this function?

Thanks!

How do I make it work along with other directives like ui-select?

I have another directive ui-select

<ui-select ng-model="step" ng-disabled="disabled">

If I add a validator to this like

<ui-select ng-model="step" ng-disabled="disabled" validator="required">

I get this error -

Error: [$compile:multidir] Multiple directives [uiSelect, validator] asking for new/isolated scope on: <div class="select2 select2-container" ng-class="{'select2-container-active select2-dropdown-open': $select.open,
                'select2-container-disabled': $select.disabled,
                'select2-container-active': $select.focus, 
                'select2-allowclear': $select.allowClear &amp;&amp; !$select.isEmpty()}" ng-model="step" ng-disabled="disabled" validator="required">

I am new to angular, and googling this didn't help much.

How to make it support multiple input box for the same validator

Hi,

Is it possible to change to the source code to make it support multiple input box for the same validator, when I click save, only the last item validated:
abc
Here is the code for the screenshot:

<td ng-repeat="model in product.models">
                            <input class="input-block-level" type="text" 
                                    ng-model="model.model_no"
                                    name="require1Watch"
                                    validator="required1"
                            >
                        </td>

Hi, come again. How to deal with conditional validation?

看了下以前的issue才发现原来你看得懂中文... 想请问下,如何能做conditional的validation。
比如说,如果我设置email,则应该只验证在输入了情况下 验证email,而在不输入email的时候,应该验证是通过的。我的意思是现在的validatior在验证的时候validator="email"跟validator="required, email"的区别只是在于 没有required的error message。
如果想validator email only if email existed,要如果做修改呢?

unique field event

There is a problem if I have some fields with the same name in various forms page
So he checks them all even though it is different form,
I just added a random number and that's how I created a unique field

Validation based on multiple inputs.

Is this possible? I tried

$validationProvider
    .setExpression({
        matching: function(value, scope, element, attrs) {
            return scope.$parent.password === scope.$parent.passwordAgain;
        }
    })
    .setDefaultMsg({
        matching: {
            error: 'Passwords do not match.'
        }
    })

But it only works on the input that was last accessed.

Doesn't Clear Errors After Submit Validate

If the form uses submit validation method and user submits, the validation errors show up on the form. However, as they type, the errors don't go away. So they never know if the problem is fixed.

Is there a way to use submit validation initially and then watch validation after the first submission?

requiredSubmit is not working with ng-include

In controller, I declare this.

$scope.user = 
    username: ''
    password: ''
    submit: () ->
      $validator.validate $scope, 'user'
      .success () ->
        Auth.signUp
          username: $scope.user.username
          password: $scope.user.password
        .then  ()->
          $location.path "/helloworld"
      .error ->
        console.log "err"

In view

 <form name="form" novalidate>
    <div ng-include="'/partials/auth/sign-up-form'">
    </div>
    <button ng-click="user.submit()" class="btn btn-lg btn-success">Sign Up</button>
</form>

/partials/auth/sign-up-form.html

<div class="input-group form-group"> 
  <span class="input-group-addon form-title">
    <label for="username">username</label>
  </span>
  <input type="text" class="form-control" id="username" ng-model="user.username" placeholder="username" validator="[required, requiredSubmit]">
</div>

When I use without ng-include, well done.
I have checked the user is same scope wheather using ng-include or not.
I can't understand what is defferent. How to can I fix it?

Support for multiple validators on a single input

I see all examples using a single validator. Any plans for building support for multiple validators on the single input.

Looking at the code i see you have used array for validator

validator.forEach(function (validation)

but the implementation does not take that into account.

Check Form Type

When using validate/reset, We have 3 types of forms

  1. single (only one model)
  2. multiple (multiple model)
  3. full object (whole form name object(

Add error class to input element on invalid data

Thanks for the great code!

It would be nice for there to be an option to add an arbitrary class to the input element when the user enters invalid data.

For example the bootstrap classes .has-errors and .has-warning.

If you are interested I can build out this functionality.

Add validation for SSN and USA/Canada phone numbers

Hey Huei,

I am thinking of adding validation for Social Security numbers(SSN) and USA/Canada phone numbers. Both of these are numbers that are only relevant to applications that deal with U.S and Canadian data.

Let me know if you are interested in having these validation types added.

Thanks!

还有一个问题需要麻烦解答一下

如果我要实现单独触发某个单独的字段验证,有没有相关的实现方式呢?我看$validationProvider.validate应该是针对于表单中所有字段的吧?因为我这里的业务是点击某个按钮,只针对于某个字段进行验证

Why default validity is false?

I think don't set validity to false when initial.

If i set a valid value to input as default value when initialize form and this input valid-method="blur", but i get this form $valid is false.

Add password validation,$submit with callback always be error

$validationProvider.setExpression({
            /**
             * @param value , user input
             * @returns {boolean} true iff valid
             */
            password: function (value) {
                return value.length >= 6 && value.length < 20;
            }
        });

        $validationProvider.setDefaultMsg({
            password: {
                error: 'error',
                success: ''
            }
        });

Validation should execute on submit?

Following the example on plunkr. The required field validation should be triggered on submit without requiring any other user interaction or filling any field.

Refactor $scope.submit

In Ordnung,

we use

$scope.submit('what hwat what')
    .success(function () { /* something */ })
    .error(function () { /* something */ });

What if we reduce this method from

<input type="submit" ng-click="something"/>

to

<input type="submit" ng-click="something" angular-validation>

Write submit action in view, not controller

How to make a confirm password validator?

Thank you for your validator gives me a lot of development to help, but I encountered a troublesome problem is how do I achieve validator password to confirm it?

Can't access $http, $q... inside .setExpression()

I cannot use $q like shown in the example unless i change the setup function to :

 var setup = function (injector) {
                this.$injector = injector;
                this.$scope = this.$injector.get('$rootScope');
                this.$http = this.$injector.get('$http');
                this.$q = this.$injector.get('$q');
                this.$timeout = this.$injector.get('$timeout');        
            };

i had to add this in front of the variables....

Customizable initial validity

The validity of the initial directive should be customizable:

ctrl.$setValidity(ctrl.$name, validity);

where validity can be a boolean set globally or locally for each directive.
It would make more sense for the form to be valid initially.
For example, you have 2 input fields in your form initially. One of them is required, the other is validated by a regex (it can be empty string as well).
You write something in the required field. Now your form theoretically should be valid, but it's not, because the other field is invalid initially, and as you didn't write anything in it, the validator didn't trigger.

嗨,我又来提问题了

最近又回到搞validation这块了,但需求是需要像密码强度提示这样的,该组件能不能做到支持一种validator提示多种信息呢?

Reset form after submit?

I'm trying to reset the form after successfully submitting but this doesnt seem to work:

vm.dataSource = {
    submit: function (form) {
        $validation.validate(form).success(function () {
            /* do stuff */
            vm.dataSource.reset(form);               
    },
    reset: function (form) {
        $validation.reset(form);
    }
};

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.