simple ng-expression not working - javascript

For validation in an Angular app, I'm trying to ensure the input value ends with the string "ism", so I'm using
ng-pattern="\b\w+(ism\b)"
This isn't triggering $invalid for the input when the expression isn't matched, however, and neither is
ng-pattern="ism$".
I'm getting an error message in the console, which seems to be saying it doesn't like the expression(s) as typed:
Error: [$parse:lexerr]
http://errors.angularjs.org/1.3.15/$parse/lexerrp0=Unexpected
%20nextharacter%20&p1=s%200-0%20%5B%5C%5D&p2=%5Cb%5Cw%2B(ism%5Cb)...

If I can understand you need something like this ng-pattern="/ism$/":
JSFiddle
<form name="myform">
<input type="text" name="test" ng-model="test" ng-pattern="/ism$/" />
<span ng-show="myform.test.$error.pattern">Not valid pattern!</span>
</form>

Thanks Michelem, that was it. To clarify the answer for others, I didn't realize the starting and ending forward slashes are required in the ng-pattern value, that was the problem. I ended up using ng-pattern="/.*ism$/", but "/\b\w+(ism\b)/" works just as well, as does "/ism$/".
The forward slashes aren't needed if one specifies the ng-pattern value as a RegExp object, e.g., ng-pattern="new RegExp('.*ism$')". It's probably better to put that RegExp into a $scope variable, if it's going to be used more than once.

Related

How to quote/write JSP variable in JavaScript inline attribute code?

I need to send variables at runtime to a js method for ajax. I am trying with this onclick function but it gives syntax error on click.:
<c:set var="abc" value="${myTaglib:getAbc()}" />
Click Here !!!
Some of these values may have spaces and decimals in them. On click, I get this error at the first occurrence of space.:
SyntaxError: missing ) after argument list
The actual HTML looks like:
<a onclick="sendAjax(240265, Workplace Ethics Exam, Company Security Policy, Friends Life, ABF/45RFG, 41444.1830)" href="#">Click Here !</a>
What is wrong with this JS call ?
Spaces in your JavaScript code are most likely a syntax error. If your values have spaces, it's best to treat them as strings.
onclick="sendAjax('${abc.firstVal}', '${abc.secVal}', ... '${abc.fifthVal}')">
If you want to use them as numbers later, you can use the JavaScript functions parseInt and parseFloat to turn strings into numbers.
Did you try leaving a space after the last curly brace?

regex (javascript) allow \w but not a single specified word

I've been banging my head against the wall and trying to google a solution for several hours with my "problem".
I need a javascript (html5 input) regex pattern, in a registration form which hasn't been submitted yet, which allows normally: ^[\w]+$ but after a submit, if the page which processes the post finds that username is already been taken, takes user back to the registration form (which is now pre-filled with the values he/she typed).
This time that "username" input field should have a pattern which don't allow user to type that same username again, but everything else will do fine.
I've played around on http://regex101.com/#javascript and came up with 100% the opposite I wanted:
^(?=[\w]*)test(?=[\w]*)$
I've been testing my pattern with string:
abctestabc
test
dfea
atest
testa
Regex I'm trying to obtain should match on everything else on my testing string, except for "test" and my pattern matches ONLY for that one.
Second pattern I came up with (which I shortly thought was what I wanted) was:
^(?:([\w]+test[\w]+)|([\w]+test|(test[\w]+)))$
..but didn't take long since I noticed that this only allows user to input:
*test
*test*
test*
..but nothing without "test" included.
First time on form:
<input type="text" name="username" pattern="^[\w]+$" />
Secound time should be:
<input type="text" name="username" pattern="**PATTERN HERE**" value="test" />
So please Stackoverflow, Pimp my regex!
user3548238, do you mean this?
^(?!test$)\w+$
This pattern will allow \w+, like before, but it will not allow "test".
This is accomplished with a lookahead.
Why don't you start pimping here ?
http://www.infotuts.com/live-username-availability-checker-and-password-strength-indicator-with-jquery-and-ajax/
DEMO

Angular.js ng-pattern strange behaviour

I have been working on a form that accepts Twitter parameters such as # and # to populate a Twitter feed.
With Angular.js I had planned to use the built in ng-pattern directive to validate the input before saving, however the validation is acting extremely strangely. It marks a "valid" string as invalid on every 2nd character of the input while typing.
Its quite hard to explain the exact behaviour so heres a Plunker.
For completeness I will add my input field with the strange ng-pattern here:
<input type="text" ng-pattern="/(^|\s)#(\w+)|(^|\s)#(\w+)/g" ng-model="foo" name="foo"/>
It's because of the global matching with the g option, it works if you take it out.
Calling test or exec multiple times involves state:
As with exec (or in combination with it), test called multiple times on the same global regular expression instance will advance past the previous match.
Basically it's trying to move on to another match, but can't find one:
a = /#(\w+)$/g;
> /#(\w+)$/g
a.exec("#test")
> ["#test", "test"]
a.exec("#test")
> null

Regex to validate textbox length

I have this RegEx that validates input (in javascript) to make sure user didn't enter more than 1000 characters in a textbox:
^.{0,1000}$
It works ok if you enter text in one line, but once you hit Enter and add new line, it stops matching. How should I change this RegEx to fix that problem?
The problem is that . doesn't match the newline character. I suppose you could use something like this:
^[.\r\n]{0,1000}$
It should work (as long as you're not using m), but do you really need a regular expression here? Why not just use the .length property?
Obligatory jwz quote:
Some people, when confronted with a problem, think "I know, I'll use regular expressions." Now they have two problems.
Edit: You could use a CustomValidator to check the length instead of using Regex. MSDN has an example available here.
What you wish is this:
/^[\s\S]{0,1000}$/
The reason is that . won't match newlines.
A better way however is to not use regular expressions and just use <text area element>.value.length
If you just want to verify the length of the input wouldn't it be easier to just verify the length of the string?
if (input.length > 1000)
// fail validation

What did I do wrong here? [Javascript Regex]

So I am writing a registration form and I need the display name to be only numbers, letters and underscores.
Have a look at my code and tell me what I'm doing wrong.
<form method="post" action="/" onsubmit="return check_form()">
<input type="text" id="display-name" name="display-name" maxlength="255" />
<input type="submit" />
</form>
<script type="text/javascript">
<!--
var name_regex = /^([a-zA-Z0-9_])+/
function check_form()
{
if (!name_regex.test(document.forms[0].elements[0].value))
{
document.forms[0].elements[0].focus()
alert("Your display name may only contain letters, numbers and underscores")
return false
}
}
-->
</script>
It's obviously been trimmed down to not include anything not related to the problem but even this snippet doesn't work.
Your regex
/^([a-zA-Z0-9_])+/
Looks for
Start of string(check), followed by
1 or more letters, numbers, or underscore (check)
And then whatever comes after it doesn't matter. This regex will match anything at all so long as it begins with a letter, number, or underscore
If you put a $ at the end, then it will work - $ matches 'end of string', so the only way it can match is if there are only numbers, letters, and underscores between the start and end of the string.
/^([a-zA-Z0-9_])+$/
Secondly, I'd suggest using document.getElementById('display-name').value instead of document.forms as it won't break if you rearrange the HTML, and is more 'the commonly accepted standard of what to do'
My regexp would go along the lines of: /^[a-zA-Z0-9_]+$/
edit: I think it's the lack of a line end $ that makes it fail.
What does "doesn't work" mean? Does it reject valid display names? Does it accept invalid display names? Which ones?
Per #Annan, leaving off the $ would make the regexp accept invalid display names like abc123!##.
If the code is rejecting valid display names, it may be because the parentheses are being matched literally instead of denoting a group (I'm not sure of the quoting convention in JS).
A simpler way to write it still would be
var name_regex = /^([a-z0-9_])+$/i;
Even simpler:
var name_regex = /^\w+$/;
I tested your script and meddled with the javascript. This seem to work:
<form method="post" action="/" onsubmit="return check_form()">
<input type="text" id="display-name" name="display-name" maxlength="255" />
<input type="submit" />
</form>
<script type="text/javascript">
<!--
var name_regex = /^([a-zA-Z0-9_])+$/;
function check_form()
{
if (!name_regex.test(document.forms[0].elements[0].value))
{
document.forms[0].elements[0].focus();
alert("Your display name may only contain letters, numbers and underscores");
return false;
}
}
-->
</script>
Sorry guys I should have been more specific. Whenever I added spaces the values were still being accepted. The dollar sign $ did the trick!
By 'not working' I take it you mean it is letting invalid entries through (rather than not letting valid entries through).
As #Annan has said, this would probably be due to the lack of the $ character at the end of the expression, as currently it only requires a single valid character at the start of the value, and the rest can be anything.

Categories