将自定义验证添加到输入字段

时间:2016-03-29 22:38:25

标签: javascript html angularjs validation

我正在尝试在我的文本输入类型上添加自定义验证。我正在使用Angular,顺便说一句。

这是代码:

<div class="form-group">
  <label class="control-label">text</label>
  <input type="text" name="text" class="form-control" id="text_test" ng-blur="saveProgress()" ng-model="formData.text" placeholder="Any text" required>
  <p class="form-group-note">
    Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
  </p>
</div>

我想添加2个验证:1)它不能为空2)文本的最小长度为6个字符。我希望在按下我的网络应用程序上的提交按钮时触发此验证。

感谢任何建议!

3 个答案:

答案 0 :(得分:0)

您可以使用HTML输入标记属性来实现此目的。

<input type="text" pattern="^.{5,}" required>

required属性告诉输入不能为空

pattern="^.{5,}"可防止输入短于6个字符。

如果<input>位于<form>之内,则会触发此验证:

<form action="">
  <input type="text" pattern="^.{5,}" required>
  <input type="submit">
</form>

如果您想详细了解该主题,请参阅MDN

答案 1 :(得分:0)

试试这个希望它会起作用

   <input type="text" name="text" class="form-control" id="text_test" ng-blur="saveProgress()" ng-model="formData.text" placeholder="Any text" required>

控制器:

   $scope.submit = function() {
        if ($scope.formData.text) {
            if ($scope.formData.text.length >= 6) {

                //save code
            } else {
                $scope.errormessage = "Min length failed ,it should be greater than 5"

            }
        } else {
            $scope.errormessage = "Textfield Empty"
        }
    };

答案 2 :(得分:0)

在键入时使用ng-minlength进行验证,

 <input type="text" name="text" class="form-control" id="text_test" ng-blur="saveProgress()" ng-model="formData.text" placeholder="Any text" required="required" ng-minlength="6"> 

仅在按下按钮后进行验证,

 <input type="text" name="text" class="form-control" id="text_test" ng-blur="saveProgress()" ng-model="formData.text" placeholder="Any text"> 


<button ng-click="submit()"/>

在您的控制器上:

 $scope.submit = function() {
        if ($scope.formData.text) {
            if ($scope.formData.text.length >= 6) {

                //save code
            } else {
                $scope.errormessage = "Min length should be greater than 5"

            }
        } else {
            $scope.errormessage = "Text field is required"
        }
    };

相关问题