Validation of forms on the client side using Angular in a Rails application

I'm facing an issue with implementing client-side validations for a devise registration form using Angular. Although I am able to add the "invalid" class to the fields as expected, I am struggling to get any output when using ng-show. There are no other Angular controllers or files involved in this project besides this one. All I have added so far is the ng-required attribute to the first_name field. Can someone help me figure out what I am doing wrong here?

Below is the code snippet:

<div class="container-fluid" ng-app>

<%= form_for(resource, as: resource_name, url: registration_path(resource_name), html: {name: "myform", "novalidate" => true}) do |f| %>
    <%= devise_error_messages! %>
    <div class="col-md-8  col-md-offset-2">
      <div class="panel panel-default">
        <div class="panel-heading"><h2>Sign up</h2></div>
        <div class="panel-body">

          <div class="col-md-12">
            <div class="row">
              <div class="col-md-6">
                <div class="form-group">
                  <%= f.label :first_name %><br />
                  <%= f.text_field :first_name, autofocus: true, "ng-model" => "myform.firstname", "ng-required": true, class: "form-control input-lg" %>
                </div>
                <p ng-show="myform.firstname.$invalid">
                  You must fill a valid name
                </p>
              </div>

              <div class="col-md-6">
                <div class="form-group">
                  <%= f.label :last_name %><br />
                  <%= f.text_field :last_name, autofocus: true, class: "form-control input-lg"%>
                </div>
              </div>
            </div>
          </div>

          <div class="form-group">
            <%= f.label :email %><br />
            <%= f.email_field :email, autofocus: true, class: "form-control input-lg" %>
          </div>

          <div class="form-group">
            <%= f.label :password %>
            <%= f.password_field :password, autocomplete: "off" , class: "form-control input-lg" %>
          </div>

          <div class="form-group">
            <%= f.label :password_confirmation %><br />
            <%= f.password_field :password_confirmation, autocomplete: "off", class: "form-control input-lg"  %>
          </div>

          <div class="actions">
            <%= f.submit "Sign up", class: "btn btn-success btn-block" %>
          </div>
<% end %>

</div>
</div>
</div>
<%= render "devise/shared/links" %>

</div>

And here is my bower file:

"dependencies": {
    "normalize-css": "normalize.css#~3.0.3",
    "bootstrap-sass": "~3.3.6",
    "angular": "~1.4.8",
    "bootstrap": "~3.3.6"
  }

Update:

I can achieve data binding successfully, indicating that Angular is functioning properly within the form. For instance, {{myform.firstname}} works fine. However, when trying to access {{myform.first_name.$valid}}, nothing is displayed. While I can see the classes being added to the input field, I can't seem to access them in this manner. I have not created a controller or module as this implementation is quite basic. Thank you for any assistance provided.

Lastly, here is the full HTML generated for the form:

<div class="container-fluid ng-scope" ng-app="">

<form name="myform" novalidate="novalidate" class="new_user ng-dirty ng-valid-parse ng-invalid ng-invalid-required" id="new_user" action="/users" accept-charset="UTF-8" method="post"><input name="utf8" type="hidden" value="✓"><input type="hidden" name="authenticity_token" value="omiBCucx+U4r9P+T0d4rQEeKhni3H4YlSPSU9FIiP4yFnMe+orTnE64czY5NSk4Yd/8ObjPFz8mlURYgOfxXhw==">

    <div class="col-md-8  col-md-offset-2">
      <div class="panel panel-default">
        <div class="panel-heading"><h2>Sign up</h2></div>
        <div class="panel-body">

          <div class="col-md-12">
            <div class="row">
              <div class="col-md-6 ng-binding">
                <div class="form-group">
                  <label for="user_first_name">First name</label><br>
                  <input autofocus="autofocus" ng-model="myform.first_name" ng-required="true" class="form-control input-lg ng-dirty ng-valid-parse ng-invalid ng-invalid-required ng-touched" type="text" name="user[first_name]" id="user_first_name" required="required">
                </div>

                <p ng-show="myform.first_name.$invalid" class="ng-hide">
                  You must fill a valid name
                </p>
              </div>

              <div class="col-md-6">
                <div class="form-group">
                  <label for="user_last_name">Last name</label><br>
                  <input autofocus="autofocus" class="form-control input-lg" type="text" name="user[last_name]" id="user_last_name">
                </div>
              </div>
            </div>
          </div>

          <div class="form-group">
            <label for="user_email">Email</label><br>
            <input autofocus="autofocus" class="form-control input-lg" type="email" value="" name="user[email]" id="user_email">
          </div>

          <div class="form-group">
            <label for="user_password">Password</label>
            <input autocomplete="off" class="form-control input-lg" type="password" name="user[password]" id="user_password">
          </div>

          <div class="form-group">
            <label for="user_password_confirmation">Password confirmation</label><br>
            <input autocomplete="off" class="form-control input-lg" type="password" name="user[password_confirmation]" id="user_password_confirmation">
          </div>

          <div class="actions">
            <input type="submit" name="commit" value="Sign up" class="btn btn-success btn-block">
          </div>

</div>
</div>
</div></form>
  <a href="/users/sign_in">Log in</a><br>







</div>

Answer №1

To update the ng-model of the input, make the following changes:

<%= f.text_field :last_name, autofocus: true, "ng-model" =>  "lastname", "ng-required": true, class: "form-control input-lg" %>

Next, modify your ng-show:

<p ng-show="myform['user[last_name]'].$invalid">

This adjustment should resolve any issues.

Note: You can omit using ng-required as you are not assessing the field's requirement. Simply utilize the html attribute required.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Testing abstract class methods in Jest can ensure full coverage

In my project, I have an abstract generic service class. export default abstract class GenericService<Type> implements CrudService<Type> { private readonly modifiedUrl: URL; public constructor(url: string) { this.modifiedUrl = ...

Alert-Enabled Random Number Generation Tool

I'm struggling to create a program that randomly generates a number between 1 and 20. If the number is less than 10, it should display "fail," and if it's greater than 10, it should display "success." I can't seem to figure out where I went ...

Struggle with registering fonts in Canvas using JavaScript

I've been struggling to add a custom font to my canvas for hosting the bot. Even though I'm not encountering any errors, the font fails to display on the host. Below is the code snippet: const { AttachmentBuilder } = require('discord.js&apos ...

Page not found: The requested file does not exist

Apache web server is claiming that the page we are attempting to reach is missing, even though we are certain it is not. It gets even more puzzling as only directory names seem to be causing issues. It's not a file permissions problem be ...

Automatically initiate a click event when the page is loaded

I'm having trouble getting a click event to trigger on my controller when the page loads. I really just want the checkboxes to be clicked automatically. <!DOCTYPE html> <html > <head> <link rel="stylesheet" type="text/css" ...

The combination of Adal with HashLocationStrategy results in an endless loop of routing

In my Angular CLI app, I am utilizing adal-angular4 for login authentication. Everything works smoothly when the app is deployed on Azure and the routing starts from the homepage with the login flow. However, if any other route is refreshed, a 404 ERROR oc ...

Tips for ensuring only one property is present in a Typescript interface

Consider the React component interface below: export interface MyInterface { name: string; isEasy?: boolean; isMedium?: boolean; isHard?: boolean; } This component must accept only one property from isEasy, isMedium, or isHard For example: <M ...

What is the best way to achieve line breaks in text that auto-wraps in JavaScript/PHP?

My resizable div contains text/sentences. As I adjust the size of the div, the text wraps itself to perfectly fit within the available space in the container div. Now, I am faced with the task of converting this dynamic text into an image using php and th ...

Steps for sending a request to the root resource

I've encountered a problem that stems from my limited knowledge of Express. Despite creating a project with Express, I'm unable to make calls to the root, only to the routes. I suspect the issue lies in my usage of app.use(...). app.js var inde ...

Connecting radio buttons to data in Vue using render/createElement

How do you connect the value of a selected radio button to a specific variable in the data object within a Vue application when using the render/createElement function? ...

Using TypeScript with Redux for Form Validation in FieldArray

My first time implementing a FieldArray from redux-form has been quite a learning experience. The UI functions properly, but there seems to be some performance issues that I need to investigate further. Basically, the concept is to click an ADD button to i ...

How can you display or conceal an HTML page in Jquery Mobile?

This code snippet is used for toggling the visibility of a div. $("[id*=viewMeButton]").click(function(){ $("[id*=viewMe]").toggle(); $("[id*=viewMeButton]").show(); }); In Jquery Mobile, similar functionality can be implemented to show/hide a ...

Transferring the link value to an AJAX function when the onclick event is triggered

I have a link containing some data. For example: <li><a href="" onclick="getcategory(this);"><?php echo $result22['category']; ?></a></li> I need this link to pass the value of $result22['category']; to ...

Using jQuery to import an external script into a React JS project

I'm looking to integrate an external JavaScript file (using jQuery) into a ReactJS project. While I found some guidance on this page, I am still encountering errors. The external JS file is named external.js: $(document).ready(function() { docu ...

First Impressions of Datatables

Is there a way to display a specific range of rows with Datatables initially? For example, showing rows 100-105 only. Does anyone know if this is achievable using the options available? ...

"Automatically close the fancybox once the form is confirmed in the AJAX success

Having an issue with closing my fancybox after submitting the registration form on my website. I am using the CMS Pro system.... Here is how I display the fancybox with the form: submitHandler: function(form) { var str = $("#subscriber_application"). ...

Modifying the color of drawings on a Javascript canvas

I am currently working on developing a drawing board using HTML and JavaScript (Node.js on the server side). One challenge I'm facing is implementing a color picker that allows users to change the paint color dynamically. While I could hard code the c ...

Finding the value of an input without having to submit it first and searching for it within a datalist

> Here is an example of HTML code <label>Person</label> <input name="PersonID" type="text" id="PersonID"> <label>Car Plate Number</label> <input name="PersonsCarPlateNumber" list="PersonsCarPlateNumbe ...

Focus Google Map on Selected Option using AngularJS

I'm attempting to center the map based on a selection in a drop-down select option box. Despite trying various examples, I haven't been successful in getting the map to recenter to the new latitude and longitude coordinates. I'd like to ach ...

Creating a double-layered donut chart with Chart.js

I'm attempting to create a unique pie chart that illustrates an array of countries on the first level and their respective cities on the second level. After modifying the data in a JSON file to align with my goal, it doesn't seem to be working a ...