Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
63
rated 0 times [  70] [ 7]  / answers: 1 / hits: 30497  / 11 Years ago, thu, august 8, 2013, 12:00:00

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.


More From » validation

 Answers
33

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


[#76460] Wednesday, August 7, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
janjadonb

Total Points: 4
Total Questions: 114
Total Answers: 118

Location: Mali
Member since Fri, Dec 3, 2021
3 Years ago
janjadonb questions
;