Solved

Input validation using AngularJS

Posted on 2014-01-22
4
1,652 Views
Last Modified: 2014-01-24
Hi Experts,

I am develpoing an application using Angularjs,html5,bootstrap ,JSON and ASP.net MVC technologies and have two textboxes in my page and if user enters a valid input (exactly 9 numbers) the input will split into 3 chunks(see working example in fiddler)
Angular Example

1)I have two functions (check fiddler) with the same funtionality for two textboxes .In the functions checking if input1 / input2 is valid then split the input into 3 chunks and display.How can I write both these functionality in Single function ?


2)When  I retrive data( using JSON) on these textboxes the input should always display in 3 chunks (111 111 111) but the input will arrive in this format(111111111).And when I try to save data I should send the data in this format (111111111) but in the UI it should always display as (111 111 111).

Now when I retrieve data in these text boxes, the input is not changing into 3 chunks. It will only change into 3 chuunks when I try to modify input.

How can I achieve this using AngularJS?

Thanks in Advance
0
Comment
Question by:ksd123
  • 2
  • 2
4 Comments
 
LVL 82

Accepted Solution

by:
leakim971 earned 500 total points
ID: 39801627
I added the nine-digit attribute on each field and create the corresponding directive:
http://jsfiddle.net/58BF2/78/

<div ng-app="App">
  <div ng-controller="Ctrl">
    <form name="myForm">
      <span>Exactly 9 digit number:</span>
      <input type="text" name="input1" ng-model="num1" ng-trim="false" nine-digit="num1" />
      <span class="error" ng-show="myForm.input1.$error.nineDigit">Numbers only!</span>
      <br />
      <span>Exactly 9 digit number:</span> 
      <input type="text" name="input2" ng-model="num2" ng-trim="false" nine-digit="num2" />
      <span class="error" ng-show="myForm.input2.$error.nineDigit">excatly 9 numbers only please!</span>
      <br />
      <button type="submit" ng-disabled="myForm.$invalid" >SAVE</button>
    </form>
  </div>
</div>

Open in new window


	var App = angular.module('App', []).controller("Ctrl",["$scope", function($scope) {

		// formData is
		// what we send to the server with Ajax
		// OR
		// what we get from the server with the Ajax
		$scope.formData = {
			num1: "123456789",
			num2: "987654321"
		};

		// this is the user inputs
		$scope.num1 = format9($scope.formData.num1);
		$scope.num2 = format9($scope.formData.num2);

	}]);

	var format9 = function(n) {
		return n.replace(/(\d{3})(\d{3})(\d{3})/g,"$1 $2 $3");
	}

	App.directive("nineDigit", function() {
		return {
			require: "ngModel",
			restrict: "A",
			link: function(scope, el, attrs, ctrl) {
				ctrl.$parsers.unshift(function(viewValue) {
					var clean = viewValue.replace(/[^\s\d]/,"");
					scope.$parent.formData[attrs.nineDigit] = clean;
					el.val(format9(clean));
					var result = /^\d{3}\s*\d{3}\s*\d{3}$/.test(clean);
					ctrl.$setValidity("nineDigit", result);
				});
			}
		}
	});

Open in new window

0
 

Author Comment

by:ksd123
ID: 39802689
Thank you so much.It' working fine.I have little bit confusion on the  link method in the custom directive.Can you briefly explain? specifically test keyword in the below code


link: function(scope, el, attrs, ctrl) {
				ctrl.$parsers.unshift(function(viewValue) {
				var clean = viewValue.replace(/[^\s\d]/,"");
				scope.$parent.formData[attrs.nineDigit] = clean;
				el.val(format9(clean));
				var result = /^\d{3}\s*\d{3}\s*\d{3}$/.test(clean); [b] //What is test here?[/b]
				ctrl.$setValidity("nineDigit", result);
				});

Open in new window

0
 
LVL 82

Expert Comment

by:leakim971
ID: 39802720
link: function(scope, el, attrs, ctrl) {
// we push a new parser at the beggining list of parser (we may use push instead unshift but to put at the end)
				ctrl.$parsers.unshift(function(viewValue) {
// we clean the value, we remove any other char than space or number b
				var clean = viewValue.replace(/[^\s\d]/,"");
// we get the nineDigit attribute value to know the associated "field" in the form
				scope.$parent.formData[attrs.nineDigit] = clean;
// we replace the value of the element by its clean version (removed other char than space and number)
				el.val(format9(clean));
// test is a regular expression function a bit like match for string. test return true of false
 //What is test here?
// We test the user input the same way you did it with ng-pattern
				var result = /^\d{3}\s*\d{3}\s*\d{3}$/.test(clean);
// we set the error status result => isValid (true or false)
				ctrl.$setValidity("nineDigit", result);
				});

Open in new window

0
 

Author Closing Comment

by:ksd123
ID: 39808272
Thanks for the explanation
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
JavaScript and Regular Expressions - How to implement date validation? 7 31
ASP.NET 5 Templates 2 65
Centered Image 2 21
Wrapper for APPs 9 31
This article demonstrates how to create a simple responsive confirmation dialog with Ok and Cancel buttons using HTML, CSS, jQuery and Promises
Boost your ability to deliver ambitious and competitive web apps by choosing the right JavaScript framework to best suit your project’s needs.
In this tutorial viewers will learn how to style elements, such a divs, with a "drop shadow" effect using the CSS box-shadow property Start with a normal styled element, such as a div.: In the element's style, type the box shadow property: "box-shad…
Video by: Mark
This lesson goes over how to construct ordered and unordered lists and how to create hyperlinks.

911 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

19 Experts available now in Live!

Get 1:1 Help Now