?
Solved

Input validation using AngularJS

Posted on 2014-01-22
4
Medium Priority
?
1,709 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 2000 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

WordPress Tutorial 2: Terminology

An important part of learning any new piece of software is understanding the terminology it uses. Thankfully WordPress uses fairly simple names for everything that make it easy to start using the software.

Question has a verified solution.

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

When it comes to write a Context Sensitive Help (an online help that is obtained from a specific point in state of software to provide help with that state) ,  first we need to make the file that contains all topics, which are given exclusive IDs. …
Not sure what the best email signature size is? Are you worried about email signature image size? Follow this best practice guide.
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…
The viewer will learn the benefit of using external CSS files and the relationship between class and ID selectors. Create your external css file by saving it as style.css then set up your style tags: (CODE) Reference the nav tag and set your prop…
Suggested Courses

762 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