0

I want to add custom validation to the angular form.

<div class="form-group" ng-class="{ 'has-error': contactform.inputAmount.$invalid && submitted }">
    <label for="inputAmount" class="col-lg-2 control-label">Amount</label>
      <div class="col-lg-10">
         <textarea ng-model="formData.inputAmount" class="validate[required,custom[comment]] feedback-input" rows="4" id="comment" name="comment" placeholder="Enter Amount to Convert" required></textarea>
     </div>
</div>

I want only number or decimal input with inverted commas like

"1"
"123.1"
"123.12221"

How can i add this pattern

Help would be highly appreciated.

Thanks

2
  • something like /^[0-9]+((\.)?[0-9]+)?$/ ? Commented Jan 8, 2016 at 5:33
  • where to add this pattern Commented Jan 8, 2016 at 5:35

2 Answers 2

1

You can use ng-pattern to validate your textarea.

Checkout here for example. http://www.java2s.com/Tutorials/AngularJS/AngularJS_Example/Directives/Use_ng_pattern_to_validate.htm

Refer here for dynamic ng-pattern validation Angularjs dynamic ng-pattern validation

Sign up to request clarification or add additional context in comments.

Comments

0

Use Directive for custom validations.

First write custom directive:

//Check For FLoat Validation
 adminApp.directive('validateFloat', function() {
 var FLOAT_REGEXP = /^\-?\d+((\.)\d+)?$/;

return {
    require: 'ngModel',
    restrict: '',
    link: function(scope, elm, attrs, ctrl) {
        // only apply the validator if ngModel is present and Angular has added the Float Number validator
        ctrl.$validators.validateFloat = function(modelValue) {
            return  ctrl.$isEmpty(modelValue) || FLOAT_REGEXP.test(modelValue);
        };

    }
};
}); 

In directive used Regex for float (or) Decimal to check with ngModel value.

Then use directive in html page.

<input type="text" name="amount" class="form-control" ng-model=test.amount" validate-float required>
                                <span class="error-container" ng-show="myForm.amount.$dirty && myForm.amount.$invalid">
                            <span ng-cloak style="color:red" ng-show="myForm.amount.$error.required">Please Enter amount</span>
                            <span ng-cloak style="color:red" ng-show="!myForm.amount.$error.required&&myForm.amount.$error.validateFloat">Enter valid amount</span>
                          </span>

In HTML page mention the custom directive "validate-float" as attribute. And for showing error message in ng-Show mention the $error.validateFloat.

For more info about directive and validations: https://docs.angularjs.org/guide/directive, https://docs.angularjs.org/guide/forms

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.