Challenges with AngularJS validation

I'm facing a couple of issues related to validation in AngularJS

Problem 1:

How can I achieve the following in the controller using AngularJS and not in the view?

vanilla js code

document.getElementById('InputId').value.length

I attempted the following in AngularJS

$scope.myForm.InputngModelName.length

Problem 2

I have a directive that validates an email

How do I invoke it from my controller?

Here is the directive code snippet

angular.module('myValidator',[])
    .directive('myValidator',function(){
            return{
                restrict: 'A',
                require: "ngModel",
                link: function(scope, elm, attrs, ctrl){
                    switch (attrs.myValidator){
                        case 'email':
                            var regex=/^[_a-z0-9]+(\.[_a-z0-9]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$/;
                            break;
                    }
                    ctrl.$parsers.unshift(function(viewValue){
                        if(regex.test(viewValue)){
                            ctrl.$setValidity('myValidator',true);
                        }
                        else{
                            ctrl.$setValidity('myValidator',false);
                        }
                        return viewValue;
                    });
                }
            };
        });    

Answer №1

If you're seeking a reliable solution for form validation in Angular, consider looking into angular-validator. This tool is lightweight and offers the flexibility to incorporate custom validation methods, including an email validator.

Angular-Validator stands out as a user-friendly, robust directive for AngularJS validation purposes.

<input  type = "email"
                            name = "emailAddress"
                            class = "form-control"
                            ng-model = "form.emailAddress"
                            invalid-message="'Thats not a real email address'"
                            required-message="'Yo this is required'"
                            validate-on="dirty"
                            required>

https://github.com/turinggroup/angular-validator http://plnkr.co/edit/XbDYKrM2QUf8g1ubTHma?p=preview

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

Dynamic content with Socket.io in Node.js

I am attempting to create a scenario where nodejs triggers an event in an irc chat that causes a html page (Running on *:3000) to execute some JavaScript. However, I am facing an issue where the showDiv(); function is not being executed as expected. Curre ...

Sort a JSON object in ascending order with JavaScript

I have a JSON object that needs to be sorted in ascending order. [{ d: "delete the text" }, { c: "copy the text" }] The keys d and c are dynamically generated and may change. How can I sort this into? [{ c: "copy the text" }, { d: "delete the text" }] ...

I encountered an issue while trying to establish a websocket connection with AngularJS

Currently, I am attempting to execute the following example However, I encountered an error message: Error: [$injector:nomod] Module 'MyApp' is not available! You either misspelled the module name or forgot to load it. If registering a module ...

What is the best way to handle waiting for an HTTP request to complete from a separate component?

https://i.sstatic.net/q4XYB.png An issue arises when calling the GetData function from a component's controller too early. I would like it to wait for the identification process to complete before triggering. During page loading, there is a server c ...

The client.postMessage() function in a service worker is not being recognized by the onmessage handler within an AngularJS controller

Handling Service Worker Messages: let angularClient; self.addEventListener('message', function(event) { // store the client that sent the message in the angularClient variable angularClient = event.ports[0]; }); Service Worker Notificat ...

How can I determine the transfer speed of a file being uploaded via jquery/Ajax?

As I upload a file using ajax/jquery, you can check out the demonstration here. The function provided will give you the percentage completion status: //progress bar function function OnProgress(event, position, total, percentComplete) { //Progress bar ...

How to use a jQuery each loop to retrieve the margin of an element

I currently have 7 different elements, each with unique margin-left and margin-top properties set in the CSS file. I am looking to loop through these elements and gather information about their margins. This is what my jQuery code looks like so far: var ...

What is the best way to run a code block every time a new reaction is added in discord.js?

I need assistance with creating a bot that can count the number of specific reactions ('⚪') to a message within a specified time frame. Additionally, I want to be able to skip the remaining time by reacting to a different emoji ('X'). ...

Issue with jSignature transitioning properly from display:none to display:block within a multi-page form

After searching through numerous resources, I have been unable to find a solution to my specific issue. I have a multi-page form that incorporates jSignature as the final tab. The structure closely follows the example from the W3Schools website, tailored t ...

Scrolling horizontally using the WinJS list view

In my project, I incorporated a WinJS list view with the display style of ms-flexbox. However, I am facing an issue where the list is scrolling horizontally beyond its width even though I have set overflow to hidden. Is there a way for me to eliminate th ...

Unable to successfully import data from vue using vue-chartjs

Encountering an error in my Vue 2 project after compilation: Failed to compile. ./node_modules/vue-chartjs/dist/index.js 85:11-26 "export 'defineComponent' was not found in 'vue' The specific line in the above file triggering thi ...

Python responding to an Ajax request using jQuery

Currently, I am experimenting with integrating a pre-built inline editor from the following source: https://github.com/wbotelhos/inplace Regrettably, the available support documentation is lacking and my expertise in Javascript, jQuery, or Ajax is limited ...

Switching between dynamic Angular template classes

Creating an Angular HTML template with reactive form: <div class= "one"> <button class = "verticalButtonClass" (click) = "onClick()"> Label4 </button> </div> <div class = "two"> </bu ...

AngularJS: Implementing similar logic with unique HTML forms and databases tailored to specific projects and clients

My current project involves developing an app that will offer the same functionality for all users, clients, or projects. However, the HTML forms displayed to users and the AJAX methods used to send data to the server will differ depending on the specific ...

Ensure there is a gap between each object when they are arranged in a

Is there a way to customize the layout of elements in the ratings view so that there is automatic spacing between them? I considered using text (white spaces) for this purpose, but it seems like an inefficient solution. Are there any other alternatives to ...

What is the best way to perform a pure JavaScript forEach loop and display the output with Firebase?

I am attempting to retrieve data from a firebase database and display all of the results. I am used to using jquery's appendTo function for this task, but I am unsure how to achieve the same result with pure javascript. Below is my current script: & ...

What could be the reason for an async function to send an empty object in the request body?

I'm currently utilizing nuxt.js, mongoDB, express, and bodyParser as well Unfortunately, the solutions provided by others do not solve my issue, as having bodyParser does not seem to fix it. The uploadPet function is designed to collect form data an ...

What is the best way to remove an element within another element using Jquery?

$(document).ready(function() { $("#movieForm").submit(function(e) { e.preventDefault(); var wordToSearch = $("#movieInput").val(); $.ajax({ url: 'http://api.rottentomatoes.com/api/public/v1.0/movies.json?apikey=x78wnu3hc3ve7amqef ...

What is the best way to align the absolute div within a relative div, which is nested inside an absolute flexContainer?

Just to clarify, I am using an absolute positioned flex container for a grid layout. Inside this flex container, there is a relative positioned element with the class .tileWrapper that expands to fill the space after the animated .tile. When I click on th ...

Is employing absolute paths in our confidential Node dependencies a good idea?

I have recently organized our codebase's React components into a separate dependency to make them reusable across different projects. To improve readability, all components now utilize Webpack aliases: import TestComponent from 'components/TestCo ...