Solved

Input validation using AngularJS

Posted on 2014-01-22
4
1,692 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

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

Not sure what the best email signature size is? Are you worried about email signature image size? Follow this best practice guide.
This article explains how to prepare an HTML email signature template file containing dynamic placeholders for users' Azure AD data. Furthermore, it explains how to use this file to remotely set up a department-wide email signature policy in Office …
In this Micro Tutorial viewers will learn how to create navigation buttons that change on rollover, using CSS (Continuation of the CSS Image Sprite tutorial) Create a parent ID for all the list items       - Specify position: absolute and display: block…
In this tutorial viewers will learn how to position overlapping items using z-index in CSS. They will also learn the restrictions on the z-index property.  Create a new HTML document with an internal stylesheet.: Create a div in CSS and name it Red.…

705 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