Search code examples
javascriptvalidationangularjsangular-uiui-validate

Angularjs Form/Field validation using JavaScript function without directives


Is there a way to validate a field in angular without using a directive? For example: I want to make following validation on an input field.

  • If field is empty we should show "Field must contain a value" message.
  • if field contains alpha Numeric characters we should show "Field can contain only digits".
  • An EVEN number - message to the user "Value must be an even number".

I want to make following validation in a call to JavaScript function.

I googled around and saw that there is a way to use ng-valid and $error , however I was not managed to make it work.

Code below is according to one of the answers I got:

<div ng-app>
<form name='theForm' novalidate>
    <input type='text' name='theText' ng-model='theText' ng-pattern='/^[0-9]+$/'/>
    <span ng-show='theForm.theText.$error.pattern'>Field can contain only digits</span>
    <span ng-show='theText.length<1'>Field must contain a value</span>
    <span ng-show='theText%2!=0&&document.getElementsByName("theText").value!=""&&!theForm.theText.$error.pattern&&!theForm.theText.$pristine'>Value must be an even number</span>
    <br/><input type='submit' value='Submit' />
</form>

I want to take what inside the last [span] and put inside a JavaScript function in order to make it more generic and eventually change only JS and not the HTML when conditions are changing

Can someone please advise? a working example would be great.


Solution

  • I'm surprised no one has mentioned ui-validate

    $scope.isOdd = function($value){
      return $value % 2;
    }
    ...
    <form name="myform">
      <input ng-model="myVal" name="value" required
        ng-pattern="/^[0-9]*$/" ui-validate=" 'isOdd($value)' "></input>
      <pre>{{myform.value.$error|json}}</pre>
    </form>
    

    Doesn't get any simpler than that, and it's PROPER AngularJS validation (not silly watches)

    Here's a working demo