How can I check if a value match certain pattern in the code?
Not use ng-pattern but in the function.
Thanks.
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.
JavaScript match() Function. The string. match() is an inbuilt function in JavaScript used to search a string for a match against any regular expression.
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 "@" .
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.
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;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With