Solved

Input validation using AngularJS

Posted on 2014-01-22
4
1,671 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

Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

Question has a verified solution.

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

This article discusses four methods for overlaying images in a container on a web page
When crafting your “Why Us” page, there are a plethora of pitfalls to avoid. Follow these five tips, and you’ll be well on your way to creating an effective page.
The viewer will learn how to create a basic form using some HTML5 and PHP for later processing. Set up your basic HTML file. Open your form tag and set the method and action attributes.: (CODE) Set up your first few inputs one for the name and …
Video by: Mark
This lesson goes over how to construct ordered and unordered lists and how to create hyperlinks.

830 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