Solved

Input validation using AngularJS

Posted on 2014-01-22
4
1,644 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
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
Thanks for the explanation
0

Featured Post

Do You Know the 4 Main Threat Actor Types?

Do you know the main threat actor types? Most attackers fall into one of four categories, each with their own favored tactics, techniques, and procedures.

Join & Write a Comment

This is a PowerShell web interface I use to manage some task as a network administrator. Clicking an action button on the left frame will display a form in the middle frame to input some data in textboxes, process this data in PowerShell and display…
Nothing in an HTTP request can be trusted, including HTTP headers and form data.  A form token is a tool that can be used to guard against request forgeries (CSRF).  This article shows an improved approach to form tokens, making it more difficult to…
In this tutorial viewers will learn how to style transparent/translucent elements using alpha transparency in CSS Start with a normal styled element, such as a div.: Define its "background-color" property as "rgba (255, 255, 255, .5): The numbers in…
In this tutorial viewers will learn how to style a corner ribbon overlay for an image using CSS Create a new class by typing ".Ribbon":  Define the class' "display:" as "inline-block": Define its "position:" as "relative": Define its "overflow:" as …

763 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

9 Experts available now in Live!

Get 1:1 Help Now