ASP.NET, JQuery - Sharing regular expressions
If you have a fair number of regular expressions used by both client (javascript) and server side code (C#, v开发者_运维知识库b.net) and want to store them in one place to avoid duplication, where do you store them?
I could use registerscript and write out the regex as strings, but just wondering if there is something more elegant.
You could store them as protected variables in your asp.net page's code-behind, and then use databinding expressions to store them as public variables in your javascript ...
In your ASPX page:
<script type="text/javascript">
var regexPhone = new RegExp("<%# regexPhone %>");
var regexEmail = new RegExp("<%# regexEmail %>");
var regexBlah = new RegExp("<%# regexBlah %>");
</script>
In your code-behind:
protected string regexPhone = "put regex string here";
protected string regexEmail = "put regex string here";
protected string regexBlah = "put regex string here";
protected void Page_Load(object sender, EventArgs e)
{
// We need to call DataBind() on the page so that
// we can use databinding expressions
DataBind();
}
While I've never tried this exact approach before, I think it would work :-P Let me know if it helps!
Note: A possible caveat here would be that the .NET Regular Expression flavor may differ from the JavaScript Regular Expression flavor. The great Jan Goyvaerts has an impressive comparison chart which may be helpful.
You could store them in a dictionary as a JSON formatted file and use it from .NET with Json.NET.
I took a look into the above two solutions but wound up doing something more prosaic. The JSON solution intrigues me, but I'm not familiar with JSON.NET and will have to try it out one day and I didn't want to store the expressions in an asp.net page, but the regex comparison chart came in handy.
I went with a simple xml file which I was using for other things, so it was there already.
For the server-side, I used the built in .NET functions to retrieve the regexes from the xml file and on the client-side, used jQuery's ajax request to get the regexes in Javascript.
$.ajax({
type: "GET",
url: "zzz.xml",
dataType: "xml",
success: parseXml
});
精彩评论