Martin Macak
Martin Macak

Reputation: 3831

Rails form validation in Angular

Suppose I have this html code

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>angular-form</title>
    <link type="text/css" rel="stylesheet" href="bower_components/bootstrap/dist/css/bootstrap.css"/>
    <link type="text/css" rel="stylesheet" href="bower_components/bootstrap/dist/css/bootstrap-theme.css"/>
    <script type="text/javascript" src="bower_components/jquery/dist/jquery.js"></script>
    <script type="text/javascript" src="bower_components/angular/angular.js"></script>
    <script type="text/javascript" src="bower_components/bootstrap/dist/js/bootstrap.js"></script>
    <script type="text/javascript">
        var app = angular.module("TestApp", []);
        app.controller('TestController', function ($scope) {
            $scope.user = {
                name: null
            };
        });
    </script>
</head>
<body ng-app="TestApp">
    <div ng-controller="TestController">
        <form name="myForm">
            <div class="form-group" ng-class="{ 'has-error': myForm.user.name.$invalid }" >
                <label for="name">Name</label>
                <input id="name" type="text" class="form-control" name="user[name]" ng-model="user.name" required />
            </div>
        </form>
    </div>
</body>
</html>

I have form called myForm and within there is field user[name], which is the way how Rails names form fields for resources. How do I bind Angular validations to such a field? I tried myform.user.name, myform.user['name'] but nothing seems to be working.

When I rename the field to 'name' and change the binding expression to myForm.name then everything works again.

How am I supposed to use Angular validations with Rails forms?

bower.json file included

{
    "name": "Test",
    "private": true,
    "ignore": [
        "**/.*",
        "node_modules"
    ],
    "dependencies": {
        "jquery": "",
        "angular": "",
        "bootstrap": ""
    }
}

Upvotes: 2

Views: 954

Answers (1)

Pankaj Parkar
Pankaj Parkar

Reputation: 136174

Inspite of doing ng-class="{ 'has-error': myForm.user.name.$invalid }" use ng-class="{ 'has-error': myForm['user[name]'].$invalid

Because if you declare scope it is showing user[name], it automatically create user[name] and that contains all validation related to field.

CODE

<div class="form-group" ng-class="{ 'has-error': myForm['user[name]'].$invalid }">
    <label for="name">Name</label>
    <input id="name" type="text" class="form-control" name="user[name]" ng-model="user.name" required />
    <button> Test</button>
</div>

Working Plunkr Here

Hope this could help you, Thanks.

Upvotes: 3

Related Questions