My application includes creating POCO classes at runtime using the CodeDOM. I am looking for a way to allow my end user to specify a limitation on the value of some properties he creates (e.g. if he adds a property Email than he would probably like to validate the content to an email address. It is obvious that the end user might have more custom restrictions).  My intention is to offer a PropertyValidation field where the end user can provide a regular expression which serve as a validator for the content of created instances of that property.  Is there any way I can make sure the string provided in the PropertyValidation field is an actual Regex before allowing it?
90846
I allow users to enter a regular expression to match IP addresses, for doing an IP filtration in a related system. I would like to validate if the entered regular expressions are valid as a lot of userse will mess op, with good intentions though.  I can of course do a Regex.IsMatch() inside a try/catch and see if it blows up that way, but are there any smarter ways of doing it? Speed is not an issue as such, I just prefer to avoid throwing exceptions for no reason.
40150
I have a form with multiple fields that I'm validating (some with methods added for custom validation) with Jörn Zaeffere's excellent jQuery Validation plugin. How do you circumvent validation with specified submit controls (in other words, fire validation with some submit inputs, but do not fire validation with others)? This would be similar to ValidationGroups with standard ASP.NET validator controls.  My situation:  It's with ASP.NET WebForms, but you can ignore that if you wish. However, I am using the validation more as a "recommendation": in other words, when the form is submitted, validation fires but instead of a "required" message displaying, a "recommendation" shows that says something along the line of "you missed the following fields.... do you wish to proceed anyways?" At that point in the error container there's another submit button now visible that can be pressed which would ignore the validation and submit anyways. How to circumvent the forms .validate() for this button control and still post?  The Buy and Sell a House sample at  allows for this in order to hit the previous links, but it does so through creating custom methods and adding it to the validator. I would prefer to not have to create custom methods duplicating functionality already in the validation plugin.  The following is a shortened version of the immediately applicable script that I've got right now:  var container = $("#&lt;%= Form.ClientID %&gt; div.validationSuggestion");  $('#&lt;%= Form.ClientID %&gt;').validate({               errorContainer: container,     errorLabelContainer: $("ul",container),     rules: {         &lt;%= YesNo.UniqueID %&gt;: { required: true },         &lt;%= ShortText.UniqueID %&gt;: { required: true } // etc.      },     messages: {         &lt;%= YesNo.UniqueID %&gt;: 'A message.',         &lt;%= ShortText.UniqueID %&gt;: 'Another message.' // etc.     },     highlight: function(element, errorClass) {         $(element).addClass(errorClass);         $(element.form).find("label[for=" + element.id + "]").addClass(errorClass);         $(element.form).find("label[for=" + element.id + "]").removeClass("valid");     },     unhighlight: function(element, errorClass) {         $(element).removeClass(errorClass);         $(element.form).find("label[for=" + element.id + "]").removeClass(errorClass);         $(element.form).find("label[for=" + element.id + "]").addClass("valid");     },     wrapper: 'li' });
81364
I'm working on a custom search page, which will search through the fields of the Project object. I use dynamic SOQL query similar to that:  String query = 'SELECT Name, Status__c ...      FROM Project__c WHERE Name LIKE \'%' + String.escapeSingleQuotes(name)      +'%\' + ' OR Status__c = \'' + String.escapeSingleQuotes(status) +'\''; List&lt;Project__c&gt; projects = Database.query(query);   But when I try to add to filter criteria Description__c field, which is Long Text Area, get the following error:  System.QueryException: field 'Description__c' can not be filtered in query call  How can I use Long Text Area fields in filtering of results?
73868
I need help. I am currently trying to test this code before uploading  public class CoreValuesExt { ApexPages.StandardController sc; public boolean readonly {get; set;} public Core_Values__c cv {get; set;} public integer countEdit = 1; public string buttonValue {get; set;} public integer recordScan;  public CoreValuesExt(ApexPages.StandardController sc) {     this.sc = sc;     cv = new Core_Values__c();     cv.Account__c = sc.getid();      readonly = true;     buttonValue = 'Edit';     recordScan = [SELECT COUNT() FROM Core_Values__c WHERE Account__c = :cv.Account__c];    if (recordScan != 0){    cv = [SELECT id, HSE__c, Professionalism_Integrity__c, Quality_Accuracy__c, Technology_Innovation__c, Timeliness__c, Value_for_money__c FROM Core_Values__c WHERE Account__c = :cv.Account__c];     }  }  public ApexPages.PageReference Save() {     return sc.Save(); }  public void ApplyAction() {     countEdit++;     Integer modolus = Math.mod(countEdit, 2);     String total = cv.HSE__c + cv.Professionalism_Integrity__c + cv.Quality_Accuracy__c + cv.Technology_Innovation__c + cv.Value_for_Money__c + cv.Timeliness__c;     if(modolus == 0)     {         readonly = false;         buttonValue = 'Save';     }     else     {         if(total != 'nullnullnullnullnullnull')            {         if (recordScan == 0){         insert cv;         readonly = true;         buttonValue = 'Edit';         }         else         {         update cv;         readonly = true;         buttonValue = 'Edit';         }         }     }    }   }  With this trigger.  trigger CoreValuesTrigger on Core_Values__c (before insert) {  Core_Values__c cvs = Trigger.new; CoreValuesExt.ApplyAction(cvs);  }   But when I try to save, I get a message saying:      Illegal assignment from List to   CoreValuesExt__Core_Values__c at line 3 column 1   "  How do I go through with this? I need help. Thanks
113594
I am working with a LINQ to SQL query and have run into an issue where I have 4 optional fields to filter the data result on.  By optional, I mean has the choice to enter a value or not.  Specifically, a few text boxes that could have a value or have an empty string and a few drop down lists that could have had a value selected or maybe not...  For example:      using (TagsModelDataContext db = new TagsModelDataContext())      {         var query = from tags in db.TagsHeaders                     where tags.CST.Equals(this.SelectedCust.CustCode.ToUpper())                      &amp;&amp; Utility.GetDate(DateTime.Parse(this.txtOrderDateFrom.Text)) &lt;= tags.ORDDTE                     &amp;&amp; Utility.GetDate(DateTime.Parse(this.txtOrderDateTo.Text)) &gt;= tags.ORDDTE                     select tags;         this.Results = query.ToADOTable(rec =&gt; new object[] { query });     }   Now I need to add the following fields/filters, but only if they are supplied by the user.   Product Number - Comes from another table that can be joined to TagsHeaders. PO Number - a field within the TagsHeaders table. Order Number - Similar to PO #, just different column. Product Status - If the user selected this from a drop down, need to apply selected value here.   The query I already have is working great, but to complete the function, need to be able to add these 4 other items in the where clause, just don't know how!
89532
Using SharePoint 2013, I have a list column of type Number, and I'd like to restrict it to either whole / half numbers, i.e. 0.5, 1, 1.5, 2, 2.5. But values such as 3.4, 2.6 wouldn't be allowed.   A choice column is unsuitable as the range users will input could go into the 100's.  Can I use custom validation on the column for this and if so how?
118546
Is there a regular expression that matches valid regular expressions?   (I know there are several flavors of regexps. One would do.)
10781
How can I specify a custom date formate to be validated with the  for jQuery?
8312
A follow-up to , and an extension of .   shows that it is possible to circumvent minimum character requirements using null bytes.  Can we exclude such non-printing characters as ASCII NULL and other control characters from counting toward minimum character requirements?  Edit: Users have demonstrated that , unmatched or invalid HTML tags, and other content that is not displayed after Markdown parsing can be used to bypass such requirements as well.  Can we cover this case as well, except for links?
19052
Is it possible to use a RegEx to validate, or sanitize Base64 data?  That's the simple question, but the factors that drive this question are what make it difficult.  I have a Base64 decoder that can not fully rely on the input data to follow the RFC specs.  So, the issues I face are issues like perhaps Base64 data that may not be broken up into 78 (I think it's 78, I'd have to double check the RFC, so don't ding me if the exact number is wrong) character lines, or that the lines may not end in CRLF; in that it may have only a CR, or LF, or maybe neither.  So, I've had a hell of a time parsing Base64 data formatted as such.  Due to this, examples like the following become impossible to decode reliably.  I will only display partial MIME headers for brevity.  Content-Transfer-Encoding: base64  VGhpcyBpcyBzaW1wbGUgQVNDSUkgQmFzZTY0IGZvciBTdGFja092ZXJmbG93IGV4YW1wbGUu   Ok, so parsing that is no problem, and is exactly the result we would expect.    And in 99% of the cases, using any code to at least verify that each char in the buffer is a valid base64 char, works perfectly.  But, the next example throws a wrench into the mix.  Content-Transfer-Encoding: base64  http://www.stackoverflow.com VGhpcyBpcyBzaW1wbGUgQVNDSUkgQmFzZTY0IGZvciBTdGFja092ZXJmbG93IGV4YW1wbGUu   This a version of Base64 encoding that I have seen in some viruses and other things that attempt to take advantage of some mail readers desire to parse mime at all costs, versus ones that go strictly by the book, or rather RFC; if you will.  My Base64 decoder decodes the second example to the following data stream.  And keep in mind here, the original stream is all ASCII data!  [0x]86DB69FFFC30C2CB5A724A2F7AB7E5A307289951A1A5CC81A5CC81CDA5B5C1B19481054D0D 2524810985CD94D8D08199BDC8814DD1858DAD3DD995C999B1BDDC8195E1B585C1B194B8   Anyone have a good way to solve both problems at once?  I'm not sure it's even possible, outside of doing two transforms on the data with different rules applied, and comparing the results.  However if you took that approach, which output do you trust?  It seems that ASCII heuristics is about the best solution, but how much more code, execution time, and complexity would that add to something as complicated as a virus scanner, which this code is actually involved in?  How would you train the heuristics engine to learn what is acceptable Base64, and what isn't?    UPDATE:  Do to the number of views this question continues to get, I've decided to post the simple RegEx that I've been using in a C# application for 3 years now, with hundreds of thousands of transactions.  Honestly, I like the answer given by  the best, which is why I picked it as the selected answer.  But to anyone using C#, and looking for a very quick way to at least detect whether a string, or byte[] contains valid Base64 data or not, I've found the following to work very well for me.  [^-A-Za-z0-9+/=]|=[^=]|={3,}$   And yes, this is just for a STRING of Base64 data, NOT a properly formatted  message.  So, if you are dealing with data of this type, please take that into account before attempting to use the above RegEx.  If you are dealing with Base16, Base32, Radix or even Base64 for other purposes (URLs, file names, XML Encoding, etc.), then it is highly recommend that you read  that  mentioned in his answer as you need to be well aware of the charset and terminators used by the implementation before attempting to use the suggestions in this question/answer set.
89886
According to the , in order to make code more portable, they recommend using something like the following for escaping data:  if (!get_magic_quotes_gpc()) {     $lastname = addslashes($_POST['lastname']); } else {     $lastname = $_POST['lastname']; }   I have other validation checks that I will be performing, but how secure is the above strictly in terms of escaping data? I also saw that magic quotes will be deprecated in PHP 6. How will that affect the above code? I would prefer not to have to rely on a database-specific escaping function like mysql_real_escape_string().
31321
I have a requirement to translate few predetermined spanish characters to english in field values of different custom objects. I have tried to create a generic code. can someone please let me know where it fails to give desired output?  Apex class snippet:  public static String translate(String str) {   M= new Map&lt;String,String&gt;{'á'=&gt;'a', 'é'=&gt;'e' ,'í'=&gt;'i', 'ó'=&gt;'o', 'ú'=&gt;'u', 'ü'=&gt;'u', 'ñ'=&gt;'n'};    for (String key: M.keyset())//iterate over keyset   {     str.replace(key,M.get(key));//Get CORR Value   }    return str;//english }
119906
Some of our form fields have character limits. We're debating whether we should reflect the current size of data entry, or to simply hard-limit and inhibit data entry beyond that size.  In HTML, simple &lt;input&gt; elements can have a maxlength attribute that inhibits further entry, but &lt;textarea&gt; has no built in option. Character limits in &lt;textarea&gt; can easily be imposed via javascript.  Twitter shows the remaining available characters, and will let you type more than that in but shows it as an error (and disables the action button).     We're looking at proactively showing the number of allowed characters for a limited field, and showing the number of characters remaining. If the user exceeds the limit then an inline form invalidation message appears.     A counter argument is that users don't even notice the little numbers updating, and that the user might well end up expending a great deal of effort typing something which they then need to trim.  What are some of the pros and cons of using these character counters?
56847
This is an extension of .  So, using the answer from the previous question I mentioned, I am able to make a generic utility that would convert/parse an Enumeration to a String.  Now the only problem I have with my solution is, I can't seem to refactor the code to my liking. It works the way I want it to, but it is a tad more on the code heavy side than I had hoped for. I was curious if there was a design pattern (or any other way to code it) to help solve this issue. I am thinking there is a creational design pattern that will help in this case. I would be easy if I had lambda expression but, Apex is not quite there yet ;).  The code I use has kind of patterns dug into it already. It uses the Strategy, Factory, and Template(ish) pattern I believe. I have the resources to find something to solve this issue (my favorite Design Pattern books), but nothing I can think of jumps out at me.  Here is the code for my utility for just one enumeration:  private interface EnumerationToStringHelper {     List&lt;Object&gt; ProvideEnumerationValues();     Boolean CompareEnumerationToString(String possibleEnumeration, Object enumerationValue); }  private class ExampleEnumToStringHelper implements EnumerationToStringHelperExampleEnum {     public List&lt;Object&gt; ProvideEnumerationValues(){ return (List&lt;Object&gt;)ExampleEnum.values(); }     public Boolean CompareEnumerationToString(String possibleEnumeration, Object enumerationValue)     {         return  ((ExampleEnum)enumerationValue).name().equalsIgnoreCase(possibleEnumeration);     } }  private static Map&lt;Type, EnumerationToStringHelper&gt; TypeToEnumerationMap;  private static void PopulateTypeToEnumerationMap() {     TypeToEnumerationMap = new Map&lt;Type, EnumerationToStringHelper&gt;     {         Type.forName('ExampleEnum') =&gt; new ExampleEnumToStringHelper()     }; }  public static Object ConvertStringToEnumeration(Type enumerationType, String possibleEnumeration) {     if(possibleEnumeration == null) return null;     if(TypeToEnumerationMap == null)         PopulateTypeToEnumerationMap();      EnumerationToStringHelper conversionAction = TypeToEnumerationMap.get(enumerationType);      if(conversionAction == null)         throw new EnumerationToStringException('The Type you enter is either a) not an enumeration or b) not a supported enumeration.');      for(Object particalarEnumValue : conversionAction.ProvideEnumerationValues())         if(conversionAction.CompareEnumerationToString(possibleEnumeration, particalarEnumValue))             return particalarEnumValue;     return null; }   public class EnumerationToStringException extends Exception { }   Now in order to use the utility, it is exactly what I hoped for.  return (ExampleEnum)RT_GeneralUtilities.ConvertStringToEnumeration(Type.forName('ExampleEnum'), 'Testing');   It is a little long, but it beats having the entire for loop for 12 or more different Enum types. That is why I wanted to build the utility - essentially for better readability and test coverage purposes.  The downside with this is I have to make a helper for every single Enum type. So it makes it kind of an eyesore maintainability-wise.    I was hoping there was a pattern I could implement to assuage that eyesore and make it appealing on both sides. Any suggestions?
16433
What characters are valid in a Java class name? What other rules govern Java class names (for instance, Java class names cannot begin with a number)?
10097
Does Java have a built-in way to escape arbitrary text so that it can be included in a regular expression? For example, if my users enter "$5", I'd like to match that exactly rather than a "5" after the end of input.
12485
I would like to do the equivalent of:  object result = Eval("1 + 3"); string now    = Eval("System.DateTime.Now().ToString()") as string   Following Biri s , I got this snippet (modified to remove obsolete method ICodeCompiler.CreateCompiler():  private object Eval(string sExpression) {     CSharpCodeProvider c = new CSharpCodeProvider();     CompilerParameters cp = new CompilerParameters();      cp.ReferencedAssemblies.Add("system.dll");      cp.CompilerOptions = "/t:library";     cp.GenerateInMemory = true;      StringBuilder sb = new StringBuilder("");     sb.Append("using System;\n");      sb.Append("namespace CSCodeEvaler{ \n");     sb.Append("public class CSCodeEvaler{ \n");     sb.Append("public object EvalCode(){\n");     sb.Append("return " + sExpression + "; \n");     sb.Append("} \n");     sb.Append("} \n");     sb.Append("}\n");      CompilerResults cr = c.CompileAssemblyFromSource(cp, sb.ToString());     if (cr.Errors.Count &gt; 0)     {         throw new InvalidExpressionException(             string.Format("Error ({0}) evaluating: {1}",              cr.Errors[0].ErrorText, sExpression));     }      System.Reflection.Assembly a = cr.CompiledAssembly;     object o = a.CreateInstance("CSCodeEvaler.CSCodeEvaler");      Type t = o.GetType();     MethodInfo mi = t.GetMethod("EvalCode");      object s = mi.Invoke(o, null);     return s;  }