how to use regex in MVC 3 with razor - asp.net-mvc

when i use MVC 3 with razor it's work fine but when i write a regex using #section head{
} that they not work
function isValidEmailAddress(emailAddress) {
var pattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(#((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(#\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
return pattern.test(emailAddress);
}
it have # so that's give me error that
Parser Error Description: An error occurred during the parsing of a
resource required to service this request. Please review the following
specific parse error details and modify your source file
appropriately. Parser Error Message: "\" is not valid at the start of
a code block. Only identifiers, keywords, comments, "(" and "{" are
valid.

A neater option is to escape the # by placing another # in front of it (##)
function isValidEmailAddress(emailAddress) {
var pattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(##((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(##\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
return pattern.test(emailAddress);
}

Add <text></text> around the function, it tells Razor to not parse the contents:
<text>
function isValidEmailAddress(emailAddress) {
var pattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(#((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(#\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
return pattern.test(emailAddress);
}
</text>

Sorry, folks, you aren't reading the error, it's complaining about the backslashes, not the #, and or #{ } don't help.

Related

How expect toMatch works?

I'm doing a POC with playwright with {expect} from '#playwright/test'.
I'm a bit confused how to create the regexp, I expect to validate this string which is correct as per the regex validator.
expect('abc123').toMatch('abc(\d+)')
first the '\' is marked as Unnecessary escape character
tried '\\' marks error
removed '\' marks error
How about toMatchText:
import { expect } from '#playwright/test';
await expect('abc123').toMatchText(/abc\d+/);
I don't see toMatch in the docs, so I used toMatchText(). I also think that capturing group in the regex () is not necessary in this example, so \d+ should be enough.
import { expect } from '#playwright/test';
let pattern = new RegExp('abc(\d+)');
const text = await page.locator('.label').textContent();
expect(text).toEqual(expect.stringMatching(pattern));
On this example you can receive a Regular Expression parameter as string and converted to a RegExp object, hence backlashes are not explicitly necessary.
Then compare with a text with expect.stringMatching as shown in the last row

What is causing this mvc razor syntax error?

var openWos = #Model.MyMaintenanceDashboard.OpenWorkOrders;
Why is Visual Studio saying this is a syntax error? It runs fine, but what would the proper syntax be?
Update: OpenWos is a javascript variable
If this is a javascript code, then you need to quote it so that you do not get the 'syntax' error.
var openWos = '#Model.MyMaintenanceDashboard.OpenWorkOrders';
If you're setting a C# var, the correct syntax would be without the # in front of Model as you're already in a C# code block:
#{
var openWos = Model.MyMaintenanceDashboard.OpenWorkOrders;
}
Edit:
You've clarified that this is a JavaScript variable. There shouldn't be a syntax error at all, as this is valid Razor. There is a distinct difference between quoting the value as suggested by Stephen, and the code that you posted originally. The type of the JavaScript variable is a string when quoted instead of a number.
For example, including this in a page:
<script>
#{ int z = 10; }
var x = #z;
console.log(x);
console.log(typeof x);
var y = '#z';
console.log(y);
console.log(typeof y);
</script>
Results in the following being logged to the console:
10
number
10
string
And there is no syntax error reported using the variable #z in either instance.
I've found that you can get around this by adding zero:
var openWos = #Model.MyMaintenanceDashboard.OpenWorkOrders + 0;

How to fix JSLint insecure ^ error?

I have following function. What this does is filters character that is allowed in a subdomain. In JSLint I got following error. Is there any way I can do this without JSLint showing error. I know I can ignore error in JSLint settings but Is there any other way I can improve my code to not show JSLint error.
function filterSubDomain(value) {
return value.replace(/[^a-z0-9\-]/ig, '')
.replace(/^[\-]*/, '')
.replace(/[\-]*$/, '')
.toLowerCase();
}
I think this is easy enough -- just a quick head rethread. I'll repeat the comment from above quickly: JSLint wants you to say what you do want rather than what you don't, because saying what you don't want always leaves room for a superset of what you do want to sneak in. That is, JSLint's intention is to force you to code explicitly/precisely.
So instead of replace, you want to use match here. Here's one way, I believe (stealing from MDN's match code a little):
/*jslint sloppy:true, white:true, devel:true */
function filterSubDomain(value) {
var out = value,
re = /[a-z0-9\-]+/gi,
found;
found = value.match(re);
out = found.join("");
// There are better ways to `trim('-')`.
while (0 === out.indexOf("-")) {
out = out.substr(1);
}
while (out.length === out.lastIndexOf("-")+1) {
out = out.slice(0,out.length-1);
}
return out;
}
console.log(filterSubDomain('---For more inform--ation, - see Chapter 3.4.5.1---'));
// Formoreinform--ation-seeChapter3451
There are other ways to trim, but you get the point. No not's in JavaScript regular expressions with JSLint!

scala-spray: why do I get escaped strings with trailing quotes?

I'm new to scala and spray and I'm having a very simple problem. I want my rest service to return unescaped strings when I return a string from a rest call, it stead i'm getting a compacted string with escapes in it. Here is my code:
Rest Service:
....
get {
respondWithMediaType(MediaTypes.`text/plain`) {
complete {
s"""
hey joe this is
"me"
bill"""
}
}
}
When I call the my service I get:
"\nhey joe this is\n\"me\"\n\bill"
But if I do a println() I see what I would expect. Please help.
I solved my own problem, it was the JSON support trait that was automatically marshalling the object
This trait Json4sSupport automatally marshal your objects as JSON hence the wrapping and compact print etc.
import spray.httpx.Json4sSupport
If you remove it you should be getting the unescaped results.
hope it helps anyone else out there.
We had the same problem using Jackson; we worked around the issue by creating an http response object instead, like so…
respondWithMediaType(`text/html`) {
complete {
new HttpResponse(StatusCodes.OK, HttpEntity(
"""
|<!DOCTYPE html>
|<html>
|<head>
|<title>Download app</title>
|</head>
|<body>
|<h2>
|Click here<br>
|</h2>
|</body>
|</html>
""".stripMargin
))
}
}

Looking for guide line about Razor syntax in asp.net mvc

i am learning asp.net mvc just going through online tutorial
1) just see <span>#model.Message</span> and #Html.Raw(model.Message)
suppose if "Hello Word" is stored in Message then "Hello Word" should display if i write statement like
<span>#model.Message</span> but i just could not understand what is the special purpose about #Html.Raw(model.Message).
what #Html.Raw() will render ?
please discuss with few more example to understand the difference well.
2) just see the below two snippet
#if (foo) {
<text>Plain Text</text>
}
#if (foo) {
#:Plain Text is #bar
}
in which version of html the tag called was introduce. is it equivalent to or what ? what is the purpose of
this tag ?
just tell me about this #:Plain Text is #bar
what is the special meaning of #: ?
if our intention is to mixing text with expression then can't we write like Plain Text is #bar
3) <span>ISBN#(isbnNumber)</span>
what it will print ? if 2000 is stored in isbnNumber variable then it may print <span>ISBN2000</span>. am i right ?
so tell me what is the special meaning of #(variable-name) why bracket along with # symbol ?
4) just see
<span>In Razor, you use the
##foo to display the value
of foo</span>
if foo has value called god then what this ##foo will print ?
5 ) see this and guide me about few more syntax given below point wise
a) #(MyClass.MyMethod<AType>())
b)
#{
Func<dynamic, object> b =
#<strong>#item</strong>;
}
#b("Bold this")
c) <div class="#className foo bar"></div>
6) see this
#functions
{
string SayWithFunction(string message)
{
return message;
}
}
#helper SayWithHelper(string message)
{
Text: #message
}
#SayWithFunction("Hello, world!")
#SayWithHelper("Hello, world!")
what they are trying to declare ? function ?
what kind of syntax it is ?
it seems that two function has been declare in two different way ? please explain this points with more sample. thanks
Few More question
7)
#{
Func<dynamic, object> b = #<strong>#item</strong>;
}
<span>This sentence is #b("In Bold").</span>
what the meaning of above line ? is it anonymous delegate?
when some one will call #b("In Bold") then what will happen ?
8)
#{
var items = new[] { "one", "two", "three" };
}
<ul>
#items.List(#<li>#item</li>)
</ul>
tell me something about List() function and from where the item variable come ?
9)
#{
var comics = new[] {
new ComicBook {Title = "Groo", Publisher = "Dark Horse Comics"},
new ComicBook {Title = "Spiderman", Publisher = "Marvel"}
};
}
<table>
#comics.List(
#<tr>
<td>#item.Title</td>
<td>#item.Publisher</td>
</tr>)
</table>
please explain briefly the above code. thanks
1) Any kind of #Variable output makes MVC automatically encode the value. That is to say if foo = "Joe & Dave", then #foo becomes Joe & Dave automatically. To escape this behavior you have #Html.Raw.
2) <text></text> is there to help you when the parser is having trouble. You have to keep in mind Razor goes in and out of HTML/Code using the semantics of the languages. that is to say, it knows it's in HTML using the XML parser, and when it's in C#/VB by its syntax (like braces or Then..End respectively). When you want to stray from this format, you can use <text>. e.g.
<ul>
<li>
#foreach (var item in items) {
#item.Description
<text></li><li></text>
}
</li>
</ul>
Here you're messing with the parser because it no longer conforms to "standard" HTML blocks. The </li> would through razor for a loop, but because it's wrapped in <text></text> it has a more definitive way of knowing where code ends and HTML begins.
3) Yes, the parenthesis are there to help give the parser an explicit definition of what should be executed. Razor makes its best attempt to understand what you're trying to output, but sometimes it's off. The parenthesis solve this. e.g.
#Foo.bar
If you only had #Foo defined as a string, Razor would inevitably try to look for a bar property because it follows C#'s naming convention (this would be a very valid notation in C#, but not our intent). So, to avoid it from continuing on we can use parenthesis:
#(Foo).bar
A notable exception to this is when there is a single trailing period. e.g.
Hello, #name.
The Razor parser realizes nothing valid (in terms of the language) follows, so it just outputs name and a period thereafter.
4) ## is the escape method for razor when you need to actually print #. So, in your example, you'd see #foo on the page in plain text. This is useful when outputting email addresses directly on the page, e.g.
bchristie##contoso.com
Now razor won't look for a contoso.com variable.
5) You're seeing various shortcuts and usages of how you bounce between valid C# code and HTML. Remember that you can go between, and the HTML you're seeing is really just a compiled IHtmlString that is finally output to the buffer.
1.
By default, Razor automatically html-encodes your output values (<div> becomes <div>). #Html.Raw should be used when you explicitly want to output the value as-is without any encoding (very common for outputting JSON strings in the middle of a <script>).
2.
The purpose of <text> and #: is to escape the regular Razor syntax flow and output literal text values. for example:
// i just want to print "Haz It" if some condition is true
#if (Model.HasSomething) { Haz It } // syntax error
#if (Model.HasSomething) { <text>Haz It</text> } // just fine
As of #:, it begins a text literal until the next line-feed (enter), so:
#if (Model.HasSomething) { #:Haz It } // syntax error, no closing '}' encountered
// just fine
#if (Model.HasSomething)
{
#:Haz It
}
3.
By default, if your # is inside a quote/double-quotes (<tr id="row#item.Id"), Razor interprets it as a literal and will not try to parse it as expression (for obvious reasons), but sometimes you do want it to, then you simply write <tr id="row#(item.Id").
4.
The purpose of ## is simply to escape '#'. when you want to output '#' and don't want Razor to interpret is as an expression. then in your case ##foo would print '#foo'.
5.
a. #(MyClass.MyMethod<AType>()) would simply output the return value of the method (using ToString() if necessary).
b. Yes, Razor does let you define some kind of inline functions, but usually you better use Html Helpers / Functions / DisplayTemplates (as follows).
c. See above.
6.
As of Razor Helpers, see http://weblogs.asp.net/scottgu/archive/2011/05/12/asp-net-mvc-3-and-the-helper-syntax-within-razor.aspx

Resources