What do I want to achieve?
I have a form with inputs that have certain types and that are required. Whenever a user clicks 'submit' I want to check whether the form passes validation or not.
This is the bare-minimum demo to show how far I got everything to work: http://jsbin.com/gokewosoti/13/edit (updated with solution)
I created the submit handler called doForm
that handles the click event on the submit button.
Inside I have access to the variable theForm
(the form's name).
According to some sources (http://blog.brunoscopelliti.com/form-validation-the-angularjs-way) I should be able to do theForm.$valid
and get a boolean showing if the form is valid or not. This turns out not to work.
It does work when I run some cumbersome code:
formy = angular.element(theForm).scope().theForm
Then suddenly formy.$valid
works.
What am I doing wrong?
The solution thanks to marked answer: http://jsbin.com/gokewosoti/14/edit
You need to pass the form to the function you are calling.
So your submit button code needs to change to this
<input type='submit' value='submit' ng-click='doForm(theForm)' />
and your doForm function needs to change to this
$scope.doForm = (theForm) ->
You'll need to delete this section to clear up errors in the console
formy = angular.element(theForm).scope().theForm
if formy.$valid == true
console.log "Wrong is valid"
else
console.log "Wrong is not valid"
So your complete submit function looks like this
$scope.doForm = (theForm) ->
# Here `theForm` is an html element, not a
# angular-ised object
# So this doesn't work:
if theForm.$valid == true
console.log "I am valid"
else
console.log "Form isn't valid"
Note that you need to put a valid email address format in the last input box to validate correctly.