Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In the angular, how can we check if a value match a pattern?

How can I check if a value match certain pattern in the code?

Not use ng-pattern but in the function.

Thanks.

like image 260
Baoyun Chen Avatar asked Aug 03 '15 07:08

Baoyun Chen


People also ask

How do you know if a string matches a pattern?

To check if a String matches a Pattern one should perform the following steps: Compile a String regular expression to a Pattern, using compile(String regex) API method of Pattern. Use matcher(CharSequence input) API method of Pattern to create a Matcher that will match the given String input against this pattern.

How do you check if a string matches a pattern in JS?

JavaScript match() Function. The string. match() is an inbuilt function in JavaScript used to search a string for a match against any regular expression.

How do I match a regex pattern?

Most characters, including all letters ( a-z and A-Z ) and digits ( 0-9 ), match itself. For example, the regex x matches substring "x" ; z matches "z" ; and 9 matches "9" . Non-alphanumeric characters without special meaning in regex also matches itself. For example, = matches "=" ; @ matches "@" .


2 Answers

Use pure javascript match function.

var str = "The rain in SPAIN stays mainly in the plain"; 
var res = str.match(/ain/g);

res will be an array with matched values. You can test if there is match checking array length:

if ( res.length > 0 ) 
    console.log("match");

from here

Use it in a directive, better as controller since in Angular 2 there would be no controllers.

like image 73
changtung Avatar answered Sep 27 '22 17:09

changtung


For HTML, you need to specify the regex in "pattern" object for e.g:

<form  name="form1" novalidate ng-submit="data.submitTheForm()">
<input type="text" placeholder="Type Here" name="inputName"  ng-model="data.inputName" required="required" pattern="^((?!_)[A-Z a-z0-9])+$" maxlength="20"/></form>

Then you need to add the condition in the controller function called on submit

 $scope.data.submitTheForm = function() {
 if($scope.form1.projectName.$error.pattern)
                {
                alert("Project name should contain only alphanumeric characters");
                return;
                }
 }
like image 37
Pravarna Bidisha Avatar answered Sep 27 '22 17:09

Pravarna Bidisha