In the angular, how can we check if a value match a pattern?
43,695
Solution 1
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.
Solution 2
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;
}
}
Author by
Baoyun Chen
Updated on May 07, 2021Comments
-
Baoyun Chen almost 3 years
How can I check if a value match certain pattern in the code?
Not use ng-pattern but in the function.
Thanks.