How can I simplify form validation?

前端 未结 11 1464
[愿得一人]
[愿得一人] 2020-12-14 00:57

The code below seems to work pretty well for doing basic required form validation.

The form displays a red Name is required message when the field is dirty

相关标签:
11条回答
  • 2020-12-14 01:51

    Consider using this ngValidate module I have been working on.

    <input name="demo-field-1" ng-model="user.name" ng-validate="customStrategy">
    

    The directive will add a span to hold your error messages. You can define custom validation strategies and individual error messages.

    ngValidateFactory.strategies.customStrategy = [
    {
        value:ngValidate.required;
        message:"This field is required"
    },
    {
        value:[ngValidate.minLength,8];
        message:"Minimum 8 characters are required"
    },
    {
        value:[myFunction,arg1,arg2];
        message:"This field fails my custom function test"
    }]
    

    demo plnkr

    0 讨论(0)
  • 2020-12-14 01:56

    I know the question is old but I want to share with the world my awesome new angular directive, I made a project on Github and I think that it just rocks compare to whatever is/was available...I based myself on the excellent Laravel PHP Framework and made it available under Angular... Enough said, let's give some examples:

    <!-- example 1 -->
    <label for="input1">Simple Integer</label>
    <input type="text" validation="integer|required" ng-model="form1.input1" name="input1" />
    
    <!-- example 2 -->
    <label for="input2">Alphanumeric + Exact(3) + required</label>
    <input type="text" validation="alpha|exact_len:3|required" ng-model="form1.input2" name="input2" />
    

    So I can define whatever amount of validation rules which I want in a simple directive validation="min_len:2|max_len:10|required|integer" and the error message will always display in the next <span> Don't you guys like it already? 1 line of code for your input, 1 line of code for the error display, you can't be simpler than that...oh and I even support your custom Regex if you want to add :)

    No more clustered Form with 10 lines of code for 1 input when the only thing you need is 2 lines, no more, even for an input with 5 validators on it. And don't worry about the form not becoming invalid, I took care of that as well, it's all handled the good way.

    Take a look at my Github project Angular-Validation and spread the word =)

    EDIT
    To make an even more smoother user experience, I added validation on timer. The concept is simple, don't bother the user while he's busy typing but do validate if he makes a pause or change input (onBlur)... Love it!!!
    You can even customize the timer as per your liking, I've decided to default it to 1 second within the directive but if you want to customize you can call as for example typing-limit="5000" to make a 5 sec. timeout. Full example:

    <input type="text" validation="integer|required" typing-limit="5000" ng-model="form1.input1" name="input1" />
    


    EDIT #2
    Also added input match confirmation validation (ex.: password confirmation), here is a sample code

    <!-- input match confirmation, as for example: password confirmation -->
    <label for="input4">Password</label>
    <input type="password" name="input4" ng-model="form1.input4" validation="alpha|min_len:4|required"  />
    <label for="input4c">Password Confirmation</label>
    <input type="password" name="input4c" ng-model="form1.input4c" validation="match:form1.input4,Password|required"  />
    

    EDIT #3
    Refactored the directive so that the requirement of having a <span> to display the error is unnecessary, the directive now handles it by itself, see the code change reflected on top.

    DEMO
    Added a live demo on Plunker

    0 讨论(0)
  • 2020-12-14 01:56

    Please use this CSS

    .myForm input.ng-invalid.ng-dirty {
        background-color: #FA787E;
    }
    
    .myForm input.ng-valid.ng-dirty {
        background-color: #78FA89;
    }
    
    0 讨论(0)
  • 2020-12-14 01:58

    One way you could do it is to abstract your validation expression to scope methods:

    PLUNKER

    HTML

    <div class="control-group" ng-class="{error: isInvalid('name')}">
      <label>Name:</label>
      <input type="text" name="name" placeholder="Name" ng-model="user.name" required/>
      <span ng-show="isInvalid('name')" class="help-inline">Name is required</span>
      <span ng-show="isValid('name')">Great!</span>
    </div>
    

    Controller

    function Ctrl($scope) {
      $scope.isInvalid = function(field){
        return $scope.myForm[field].$invalid && $scope.myForm[field].$dirty;
      };
    
      $scope.isValid = function(field){
        return $scope.myForm[field].$valid && $scope.myForm[field].$dirty;
      };
    
    }
    
    0 讨论(0)
  • 2020-12-14 01:59

    index.php

    <form class="add-task" id="myForm" name="myForm" method="post" ng-submit="submitForm(myForm.$valid)" novalidate>
       <div class="form-actions">
          <!-- ng-patten for validation -->
          <span class="error" ng-show="myForm.username.$error.required">
          Required!</span> 
          <div class="input-group">
             <input type="text"  ng-model="user2.username"  name="username" ng-pattern="example.word" placeholder="User Name" required>
             <input  type="password"  ng-model="user2.password"   name="password" placeholder="user password" ng-minlength="4"
                ng-maxlength="10" required>
             <button class="btn btn-success" ng-show="displayadd" type="submit"  ng-click="addUser(user2)" ng-disabled="myForm.$invalid"><i class="glyphicon glyphicon-plus"></i> Add New user</button>
             <button class="btn btn-default" ng-show="displayupdate"  ng-click="updateUser(user2)" value="Update"ng-disabled="myForm.$invalid"><span class="glyphicon glyphicon-save"></span>Save Change</button>
             <p style="color:red" ng-show="myForm.password.$error.minlength" class="help-block">Password Is Very Short.</p>
             <p style="color:red"  ng-show="myForm.password.$error.maxlength" class="help-block">Password Is Very Long.</p>
          </div>
       </div>
    </form>
    

    In app.js include this function :

     $scope.submitForm = function() {
         if ($scope.myForm.$valid) {
             alert('Our Form Is Submited....');
         }
     };
    
    0 讨论(0)
提交回复
热议问题