Search Results

Search found 18876 results on 756 pages for 'request validation'.

Page 4/756 | < Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >

  • Creating Custom validation rule and register it

    - by FormsEleven
    What is Validation Rule? A validation rule is a piece of code that performs some check ensuring that data meets given constraints.In an enterprise application development environment, often it might require developers to have validation be performed based on some logic at several places across projects. Instead of redundant validation creation, a custom validation rule provides a library with a validation rules that can be registered and used across applications.A custom Validation is encapsulated in a reusable component so that you do not have to write it every time when you need to do input validation. Here is how we can easily implement a custom validation that checks for name of an employee to be "KING" For creating a custom Validation , 1.         Create Generic Application Workspace "CustomValidator" with the project "Model" 2.         Create an BC4J based on emp table. 3.         Create a custom validation rule.In EmpNamerule class, update the validateValue(..) method as follows:  public boolean validateValue(Object value) { EntityImpl emp = (EntityImpl)value; if(emp.getAttribute("Ename").toString().equals("KING")){ return false; } return true; } Create ADF Library: Next step would be to create ADF library. Create ADF library with name lets say testADFLibrary1.jarRegister ADF Library Next step is to register the ADF library , so that its available across the applications. Invoke the menu "Tools -> Preferences"Select the option "Business Components -> Registered Rules" from left paneClick on button "Pick Library". The dialog "Select Library" comes up with  the user library addedAdd new library' that points to the above jarCheck the checkbox "Register" and set the name for the rule Sample UsageHere is how we can easily implement a validation rule that restrict the name of the employee not to be "KING".Create new Application with BC4J based on EMP table.Create new validation under Business rule tab for Ename & select the above custom validation rule.Run the AppModule tester.

    Read the article

  • Introducing Data Annotations Extensions

    - by srkirkland
    Validation of user input is integral to building a modern web application, and ASP.NET MVC offers us a way to enforce business rules on both the client and server using Model Validation.  The recent release of ASP.NET MVC 3 has improved these offerings on the client side by introducing an unobtrusive validation library built on top of jquery.validation.  Out of the box MVC comes with support for Data Annotations (that is, System.ComponentModel.DataAnnotations) and can be extended to support other frameworks.  Data Annotations Validation is becoming more popular and is being baked in to many other Microsoft offerings, including Entity Framework, though with MVC it only contains four validators: Range, Required, StringLength and Regular Expression.  The Data Annotations Extensions project attempts to augment these validators with additional attributes while maintaining the clean integration Data Annotations provides. A Quick Word About Data Annotations Extensions The Data Annotations Extensions project can be found at http://dataannotationsextensions.org/, and currently provides 11 additional validation attributes (ex: Email, EqualTo, Min/Max) on top of Data Annotations’ original 4.  You can find a current list of the validation attributes on the afore mentioned website. The core library provides server-side validation attributes that can be used in any .NET 4.0 project (no MVC dependency). There is also an easily pluggable client-side validation library which can be used in ASP.NET MVC 3 projects using unobtrusive jquery validation (only MVC3 included javascript files are required). On to the Preview Let’s say you had the following “Customer” domain model (or view model, depending on your project structure) in an MVC 3 project: public class Customer { public string Email { get; set; } public int Age { get; set; } public string ProfilePictureLocation { get; set; } } .csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; } When it comes time to create/edit this Customer, you will probably have a CustomerController and a simple form that just uses one of the Html.EditorFor() methods that the ASP.NET MVC tooling generates for you (or you can write yourself).  It should look something like this: With no validation, the customer can enter nonsense for an email address, and then can even report their age as a negative number!  With the built-in Data Annotations validation, I could do a bit better by adding a Range to the age, adding a RegularExpression for email (yuck!), and adding some required attributes.  However, I’d still be able to report my age as 10.75 years old, and my profile picture could still be any string.  Let’s use Data Annotations along with this project, Data Annotations Extensions, and see what we can get: public class Customer { [Email] [Required] public string Email { get; set; }   [Integer] [Min(1, ErrorMessage="Unless you are benjamin button you are lying.")] [Required] public int Age { get; set; }   [FileExtensions("png|jpg|jpeg|gif")] public string ProfilePictureLocation { get; set; } } .csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; } Now let’s try to put in some invalid values and see what happens: That is very nice validation, all done on the client side (will also be validated on the server).  Also, the Customer class validation attributes are very easy to read and understand. Another bonus: Since Data Annotations Extensions can integrate with MVC 3’s unobtrusive validation, no additional scripts are required! Now that we’ve seen our target, let’s take a look at how to get there within a new MVC 3 project. Adding Data Annotations Extensions To Your Project First we will File->New Project and create an ASP.NET MVC 3 project.  I am going to use Razor for these examples, but any view engine can be used in practice.  Now go into the NuGet Extension Manager (right click on references and select add Library Package Reference) and search for “DataAnnotationsExtensions.”  You should see the following two packages: The first package is for server-side validation scenarios, but since we are using MVC 3 and would like comprehensive sever and client validation support, click on the DataAnnotationsExtensions.MVC3 project and then click Install.  This will install the Data Annotations Extensions server and client validation DLLs along with David Ebbo’s web activator (which enables the validation attributes to be registered with MVC 3). Now that Data Annotations Extensions is installed you have all you need to start doing advanced model validation.  If you are already using Data Annotations in your project, just making use of the additional validation attributes will provide client and server validation automatically.  However, assuming you are starting with a blank project I’ll walk you through setting up a controller and model to test with. Creating Your Model In the Models folder, create a new User.cs file with a User class that you can use as a model.  To start with, I’ll use the following class: public class User { public string Email { get; set; } public string Password { get; set; } public string PasswordConfirm { get; set; } public string HomePage { get; set; } public int Age { get; set; } } Next, create a simple controller with at least a Create method, and then a matching Create view (note, you can do all of this via the MVC built-in tooling).  Your files will look something like this: UserController.cs: public class UserController : Controller { public ActionResult Create() { return View(new User()); }   [HttpPost] public ActionResult Create(User user) { if (!ModelState.IsValid) { return View(user); }   return Content("User valid!"); } } .csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; } Create.cshtml: @model NuGetValidationTester.Models.User   @{ ViewBag.Title = "Create"; }   <h2>Create</h2>   <script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script> <script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>   @using (Html.BeginForm()) { @Html.ValidationSummary(true) <fieldset> <legend>User</legend> @Html.EditorForModel() <p> <input type="submit" value="Create" /> </p> </fieldset> } .csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; } In the Create.cshtml view, note that we are referencing jquery validation and jquery unobtrusive (jquery is referenced in the layout page).  These MVC 3 included scripts are the only ones you need to enjoy both the basic Data Annotations validation as well as the validation additions available in Data Annotations Extensions.  These references are added by default when you use the MVC 3 “Add View” dialog on a modification template type. Now when we go to /User/Create we should see a form for editing a User Since we haven’t yet added any validation attributes, this form is valid as shown (including no password, email and an age of 0).  With the built-in Data Annotations attributes we can make some of the fields required, and we could use a range validator of maybe 1 to 110 on Age (of course we don’t want to leave out supercentenarians) but let’s go further and validate our input comprehensively using Data Annotations Extensions.  The new and improved User.cs model class. { [Required] [Email] public string Email { get; set; }   [Required] public string Password { get; set; }   [Required] [EqualTo("Password")] public string PasswordConfirm { get; set; }   [Url] public string HomePage { get; set; }   [Integer] [Min(1)] public int Age { get; set; } } .csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; } Now let’s re-run our form and try to use some invalid values: All of the validation errors you see above occurred on the client, without ever even hitting submit.  The validation is also checked on the server, which is a good practice since client validation is easily bypassed. That’s all you need to do to start a new project and include Data Annotations Extensions, and of course you can integrate it into an existing project just as easily. Nitpickers Corner ASP.NET MVC 3 futures defines four new data annotations attributes which this project has as well: CreditCard, Email, Url and EqualTo.  Unfortunately referencing MVC 3 futures necessitates taking an dependency on MVC 3 in your model layer, which may be unadvisable in a multi-tiered project.  Data Annotations Extensions keeps the server and client side libraries separate so using the project’s validation attributes don’t require you to take any additional dependencies in your model layer which still allowing for the rich client validation experience if you are using MVC 3. Custom Error Message and Globalization: Since the Data Annotations Extensions are build on top of Data Annotations, you have the ability to define your own static error messages and even to use resource files for very customizable error messages. Available Validators: Please see the project site at http://dataannotationsextensions.org/ for an up-to-date list of the new validators included in this project.  As of this post, the following validators are available: CreditCard Date Digits Email EqualTo FileExtensions Integer Max Min Numeric Url Conclusion Hopefully I’ve illustrated how easy it is to add server and client validation to your MVC 3 projects, and how to easily you can extend the available validation options to meet real world needs. The Data Annotations Extensions project is fully open source under the BSD license.  Any feedback would be greatly appreciated.  More information than you require, along with links to the source code, is available at http://dataannotationsextensions.org/. Enjoy!

    Read the article

  • Spring MVC validation with Annotations

    - by cdecker
    I'm having quite some trouble since I migrated my controllers from classical inheritance to use the annotations like @Controller and @RequestMapping. The problem is that I don't know how to plug in validation like in the old case. Are there any good tutorials about this?

    Read the article

  • minLength data validation is not working with Auth component for CakePHP

    - by grokker
    Let's say I have a user registration and I'm using the Auth component (/user/register is allowed of course). The problem is if I need to set a minLength validation rule in the model, it doesn't work since the Auth component hashes the password therefore it's always more than my minlength password and it passes even if it's blank. How do I fix this issue? Thanks in advance!

    Read the article

  • Only 192.168.0.3 can request, but anyone can request /public/file.html

    - by mattalexx
    I have the following virtual host on my development server: <VirtualHost *:80> ServerName example.com DocumentRoot /srv/web/example.com/pub <Directory /srv/web/example.com/pub> Order Deny,Allow Deny from all Allow from 192.168.0.3 </Directory> </VirtualHost> The Allow from 192.168.0.3 part is to only allow requests from my workstation machine. I want to tweak this to allow anyone to request a certain URL: http://example.com/public/file.html How do I change this to allow /public/file.html requests to get through from anyone? Note: /public/file.html doesn't actually exist as a file on the server. I redirect all incoming requests through a single index file using mod_rewrite.

    Read the article

  • What should a domain object's validation cover?

    - by MarcoR88
    I'm trying to figure out how to do validation of domain objects that need external resources, such as data mappers/dao Firstly here's my code class User { const INVALID_ID = 1; const INVALID_NAME = 2; const INVALID_EMAIL = 4; int getID(); void setID(Int i); string getName(); void setName(String s); string getEmail(); void setEmail(String s); int getErrorsForInsert(); // returns a bitmask for INVALID_* constants int getErrorsForUpdate(); } My worries are about the uniqueness of the email, checking it would require the storage layer. Reading others' code seems that two solutions are equally accepted: both perform the unique validation in data mapper but some set an error state to the DO user.addError(User.INVALID_EMAIL) while others prefer to throw a totally different type of exception that covers only persistence, like: UserStorageException { const INVALID_EMAIL = 1; const INVALID_CITY = 2; } What are the pros and cons of these solutions?

    Read the article

  • adding Form Validation Javacript of jquery???

    - by user634599
    How can I add inline Validation to make sure a choice of radio input must be selected <script type="text/javascript"> function choosePage() { if(document.getElementById('weightloss').form1_option1.checked) { window.location.replace( "http://google.com/" ); } if(document.getElementById('weightloss').form1_option2.checked) { window.location.replace( "http://yahoo.com/" ); } } </script> <form id="weightloss"> <input type="radio" id="form1_option1" name="weight-loss" value="5_day" class="plan"> <label for="form1_option1"> 5 Day - All Inclusive Price</label><br> <input type="radio" id="form1_option2" name="weight-loss" value="7_day"> <label for="form1_option2"> 7 Day - All Inclusive Price</label><br> <input type="button" value="Place Order" alt="Submit button" class="orange_btn" onclick="choosePage()"> </form>

    Read the article

  • Javascript form validation - multiple form fields larger than 0

    - by calebface
    function negativeValues(){ var myTextField = document.getElementById('digit'); if(myTextField.value < 0) { alert("Unable to submit as one field has a negative value"); return false; } } Above is a Javascript piece of code where every time a field id 'digit' has a value that's less than 0, than an alert box appears either onsubmit or onclick in the submit button. There are about 50 fields in the form that should be considered 'digit' fields where they shouldn't be anything less than 0. What should I change with this Javascript to ensure that all 'digit' like fields have this alert box pop up? I cannot use jquery/mootools for validation - it has to be flat Javascript. Thanks.

    Read the article

  • jQuery Validation plugin: prompt for override

    - by Sam Carleton
    I have a jQuery form that has validation of a sort. It is a data entry screen with two 'recommend ranges', one is 36-84, the other 50-300. The business rules call for the values to be either blank or greater than zero, but to prompt for confirmation if the values are outside of the range listed above. I have seen some other threads that talk about setting the class="cancel" on the submit button. From what I can tell, this will simply disable the validation. I need to prompt for a "do you want to continue, yes or no?" and if no stop the submit, if yes, continue. Below is an example from the book Pro jQuery. By default the top row needs to be between 10 and 20 to submit. How would you change it so that it prompts you and if you say Yes it submits, no prevents the submit: <!DOCTYPE html> <html> <head> <title>Example</title> <script src="jquery-1.7.js" type="text/javascript"></script> <script src="jquery.tmpl.js" type="text/javascript"></script> <script src="jquery.validate.js" type="text/javascript"></script> <style type="text/css"> h1 { min-width: 70px; border: thick double black; margin-left: auto; margin-right: auto; text-align: center; font-size: x-large; padding: .5em; color: darkgreen; background-image: url("border.png"); background-size: contain; margin-top: 0; } .dtable {display: table;} .drow {display: table-row;} .dcell {display: table-cell; padding: 10px;} .dcell > * {vertical-align: middle} input {width: 2em; text-align: right; border: thin solid black; padding: 2px;} label {width: 5em; padding-left: .5em; display: inline-block;} #buttonDiv {text-align: center;} #oblock {display: block; margin-left: auto; margin-right: auto; min-width: 700px; } div.errorMsg {color: red} .invalidElem {border: medium solid red} </style> <script type="text/javascript"> $(document).ready(function() { var data = [ { name: "Astor", product: "astor", stocklevel: "10", price: "2.99"}, { name: "Daffodil", product: "daffodil", stocklevel: "12", price: "1.99"}, { name: "Rose", product: "rose", stocklevel: "2", price: "4.99"}, { name: "Peony", product: "peony", stocklevel: "0", price: "1.50"}, { name: "Primula", product: "primula", stocklevel: "1", price: "3.12"}, { name: "Snowdrop", product: "snowdrop", stocklevel: "15", price: "0.99"}, ]; var templResult = $('#flowerTmpl').tmpl(data); templResult.slice(0, 3).appendTo('#row1'); templResult.slice(3).appendTo("#row2"); $('form').validate({ highlight: function(element, errorClass) { $(element).add($(element).parent()).addClass("invalidElem"); }, unhighlight: function(element, errorClass) { $(element).add($(element).parent()).removeClass("invalidElem"); }, errorElement: "div", errorClass: "errorMsg" }); $.validator.addClassRules({ flowerValidation: { required: true, min: 0, max: 100, digits: true, } }) $('#row1 input').each(function(index, elem) { $(elem).rules("add", { min: 10, max: 20 }) }); $('input').addClass("flowerValidation").change(function(e) { $('form').validate().element($(e.target)); }); }); </script> <script id="flowerTmpl" type="text/x-jquery-tmpl"> <div class="dcell"> <img src="${product}.png"/> <label for="${product}">${name}: </label> <input name="${product}" value="0" required /> </div> </script> </head> <body> <h1>Jacqui's Flower Shop</h1> <form method="post" action="http://node.jacquisflowershop.com/order"> <div id="oblock"> <div class="dtable"> <div id="row1" class="drow"> </div> <div id="row2"class="drow"> </div> </div> </div> <div id="buttonDiv"><button type="submit">Place Order</button></div> </form> </body> </html>

    Read the article

  • A simple example of validation in ASP.Net applications

    - by nikolaosk
    I am going to start a new series of posts and I am going to cover in depth all the validation mechanisms/techniques/controls we have available in our ASP.Net applications. As many of you may know I am a Microsoft Certified Trainer and I will present this series of posts from a trainer's point of view. This series of posts will be helpful to all of novice/intermediate programmers who want to see all the tools available for validating data in ASP.Net applications. I am not going to try to convince...(read more)

    Read the article

  • A potentially dangerous Request.Form value was detected: Dealing with these errors proactively, or a

    - by Albert
    I'm noticing this error more and more in my error logs. I've read through the questions here talking about this error, but they don't address what I would like to do (see below). I'm considering three options, in the order of preference: 1) When submitting a form (I use formviews almost exclusively, if that helps), if potentially dangerous characters are detected, automatically strip them out and submit. 2) When submitting a form, if potentially dangerous characters are detected, alert the user and let them fix it before trying again. 3) After the exception is generated, deal with it and alert the user. I'm hoping one of the first two options might be able to do somewhat globally...I know for the 3rd I'd have to alter a TON of Try-Catch blocks I already have in place. Doable, but labor intensive. I'd rather be proactive about it if at all possible and avoid the exception all together. Perhaps one approach to #1 would be to write a block of code that could loop through all text entry fields in a formview, during the insert/update event, and strip the characters out. I'm ok with that, but I'd rather not have to heavily alter all my Insert/Update events to accomplish this. Or maybe I just create a different class to do the text checking/deleting, and only insert 1 line of code in each Insert/Update event. If anyone can come up with some example code of any of these approaches that would be a help. Thanks for any ideas or information. I'm definitely open to other solutions too; these are only the 3 that came to mind. I can say that I don't want to turn request validation off though.

    Read the article

  • W3 xHTML Validation Errors on jQuery code!

    - by Chris
    I have some jQuery code that, without it in the document it passes validation fine, but with it in it causes errors. The code in question is here: $.ajax({ type: "GET", url: "data.xml", dataType: "xml", success: function(xml) { //Update error info errors = $(xml).find("Errors").find("*").filter(function () { return $(this).children().length === 0; }); if (errors.length == 0) { statuscontent = "<img src='/web/resources/graphics/accept.png' alt='' /> System OK"; } else { statuscontent = "<img src='/web/resources/graphics/exclamation.png' alt='' /> "+errors.length+" System error"+(errors.length>1?"s":""); } $("#top-bar-systemstatus a").html(statuscontent); //Update timestamp $("#top-bar-timestamp").html($(xml).find("Timestamp").text()); //Update storename $("#top-bar-storename").html("Store: "+$(xml).find("StoreName").text()); } }); There are loads of other jQuery code on the page which all works fine and causes no errors so I cannot quite understand what is wrong with this. The page isn't "live" so cannot provide a link to it unfortunately. The error it lists is document type does not allow element "img" here And the line of code it points to is here: statuscontent = "<img src='/web/resources/graphics/accept.png' alt='' /> System OK"; It also has an issue with the next assignment to statuscontent

    Read the article

  • Spring validation errors not displayed

    - by Art Vandelay
    I have the following situation. I have a validator to validate my command object and set the errors on a Errors object to be displayed in my form. The validator is invoked as expected and works okay, but the errors i set on the Errors objects are not displayed, when i am sent back to my form because of the validation errors. Validator: public void validate(Object obj, Errors err) { MyCommand myCommand = (MyCommand) obj; int index = 0; for (Field field : myCommand.getFields()) { if (field.isChecked()) { if ((field.getValue() == null) || (field.getValue().equals(""))) { err.rejectValue("fields[" + index + "].value", "errors.missing"); } } index++; } if (myCommand.getLimit() < 0) { err.rejectValue("limit", "errors.invalid"); } } Command: public class MyCommand { private List<Field> fields; private int limit; //getters and setters } public class Field { private boolean checked; private String name; private String value; //getters and setters } Form: <form:form id="myForm" method="POST" action="${url}" commandName="myCommand"> <c:forEach items="${myCommand.fields}" var="field" varStatus="status"> <form:checkbox path="fields[${status.index}].checked" value="${field.checked}" /> <c:out value="${field.name}" /> <form:input path="fields[${status.index}].value" /> <form:errors path="fields[${status.index}].value" cssClass="error" /></td> <form:hidden path="fields[${status.index}].name" /> </c:forEach> <fmt:message key="label.limit" /> <form:input path="limit" /> <form:errors path="limit" cssClass="error" /> </form:form> Controller: @RequestMapping(value = REQ_MAPPING, method = RequestMethod.POST) public String onSubmit(Model model, MyCommand myCommand, BindingResult result) { // validate myCommandValidator.validate(myCommand, result); if (result.hasErrors()) { model.addAttribute("myCommand", myCommand); return VIEW; } // form is okay, do stuff and redirect } Could it be that the paths i give in the validator and tag are not correct? The validator validates a command object containing a list of objects, so that's why i give a index on the list in the command object when registering an error message (for example: "fields["+index+"]".value). Or is it that the Errors object containing the errors is not available to my view? Any help is welcome and appreciated, it might give me a hint or point me in right direction.

    Read the article

  • client side validation in ascx files (user controls) for asp.net mvc

    - by Sefer KILIÇ
    hi, I have a logOn forn in ascx files and I render it as partial. How I can add a clinet side validation to this form, have any idea ? My below code does not work <%= Html.ValidationSummary(true, "Giris basarisiz oldu. Lütfen hatalari düzeltip tekrar deneyin.") %> <% Html.EnableClientValidation(); %> <% using (Html.BeginForm("LogOnProcess", "Account")) { %> <div> <fieldset> <legend>Hesap Bilgileri</legend> <div class="editor-label"> <%= Html.LabelFor(m => m.UserName) %> </div> <div class="editor-field"> <%= Html.TextBoxFor(m => m.UserName) %> <%= Html.ValidationMessageFor(m => m.UserName) %> </div> <div class="editor-label"> <%= Html.LabelFor(m => m.Password) %> </div> <div class="editor-field"> <%= Html.PasswordFor(m => m.Password) %> <%= Html.ValidationMessageFor(m => m.Password) %> </div> <div class="editor-label"> <%= Html.CheckBoxFor(m => m.RememberMe) %> <%= Html.LabelFor(m => m.RememberMe) %> </div> <p> <input type="submit" value="Giris" /> </p> </fieldset> </div> <% } %>

    Read the article

  • ASP.NET MVC 2 client-side validation rules not being created

    - by Brant Bobby
    MVC isn't generating the client-side validation rules for my viewmodel. The HTML just contains this: <script type="text/javascript"> //<![CDATA[ if (!window.mvcClientValidationMetadata) { window.mvcClientValidationMetadata = []; } window.mvcClientValidationMetadata.push({"Fields":[],"FormId":"form0","ReplaceValidationSummary":false}); //]]> </script> Note that Fields[] is empty! My view is strongly-typed and uses the new strongly-typed HTML helpers (TextBoxFor(), etc). View Model / Domain Model public class ItemFormViewModel { public Item Item { get; set; } [Required] [StringLength(100)] public string Whatever { get; set; } // for demo } [MetadataType(typeof(ItemMetadata))] public class Item { public string Name { get; set; } public string SKU { get; set; } public int QuantityRequired { get; set; } // etc. } public class ItemMetadata { [Required] [StringLength(100)] public string Name { get; set; } [Required] [StringLength(50)] public string SKU { get; set; } [Range(0, Int32.MaxValue)] public int QuantityRequired { get; set; } // etc. } (I know I'm using a domain model as my / as part of my view model, which isn't a good practice, but disregard that for now.) View <%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<ItemFormViewModel>" %> <asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server"> <h2>Editing item: <%= Html.Encode(Model.Item.Name) %></h2> <% Html.EnableClientValidation(); %> <%= Html.ValidationSummary("Could not save the item.") %> <% using (Html.BeginForm()) { %> <%= Html.TextBoxFor(model => model.Item.Name) %> <%= Html.TextBoxFor(model => model.Item.SKU) %> <%= Html.TextBoxFor(model => model.Item.QuantityRequired) %> <%= Html.HiddenFor(model => model.Item.ItemID) %> <%= Html.TextBox("Whatever", Model.Whatever) %> <input type="submit" value="Save" /> <% } %> </asp:Content> I included the Whatever property on the view model because I suspected that MVC wasn't recursively inspecting the sub-properties of ItemFormViewModel.Item, but even that isn't being validated? I've even tried delving into the MVC framework source code but have come up empty. What could be going on?

    Read the article

  • Writing Unit Tests for an ASP.NET MVC Action Method that handles Ajax Request and Normal Request

    - by shiju
    In this blog post, I will demonstrate how to write unit tests for an ASP.NET MVC action method, which handles both Ajax request and normal HTTP Request. I will write a unit test for specifying the behavior of an Ajax request and will write another unit test for specifying the behavior of a normal HTTP request. Both Ajax request and normal request will be handled by a single action method. So the ASP.NET MVC action method will be execute HTTP Request object’s IsAjaxRequest method for identifying whether it is an Ajax request or not. So we have to create mock object for Request object and also have to make as a Ajax request from the unit test for verifying the behavior of an Ajax request. I have used NUnit and Moq for writing unit tests. Let me write a unit test for a Ajax request Code Snippet [Test] public void Index_AjaxRequest_Returns_Partial_With_Expense_List() {     // Arrange       Mock<HttpRequestBase> request = new Mock<HttpRequestBase>();     Mock<HttpResponseBase> response = new Mock<HttpResponseBase>();     Mock<HttpContextBase> context = new Mock<HttpContextBase>();       context.Setup(c => c.Request).Returns(request.Object);     context.Setup(c => c.Response).Returns(response.Object);     //Add XMLHttpRequest request header     request.Setup(req => req["X-Requested-With"]).         Returns("XMLHttpRequest");       IEnumerable<Expense> fakeExpenses = GetMockExpenses();     expenseRepository.Setup(x => x.GetMany(It.         IsAny<Expression<Func<Expense, bool>>>())).         Returns(fakeExpenses);     ExpenseController controller = new ExpenseController(         commandBus.Object, categoryRepository.Object,         expenseRepository.Object);     controller.ControllerContext = new ControllerContext(         context.Object, new RouteData(), controller);     // Act     var result = controller.Index(null, null) as PartialViewResult;     // Assert     Assert.AreEqual("_ExpenseList", result.ViewName);     Assert.IsNotNull(result, "View Result is null");     Assert.IsInstanceOf(typeof(IEnumerable<Expense>),             result.ViewData.Model, "Wrong View Model");     var expenses = result.ViewData.Model as IEnumerable<Expense>;     Assert.AreEqual(3, expenses.Count(),         "Got wrong number of Categories");         }   In the above unit test, we are calling Index action method of a controller named ExpenseController, which will returns a PartialView named _ExpenseList, if it is an Ajax request. We have created mock object for HTTPContextBase and setup XMLHttpRequest request header for Request object’s X-Requested-With for making it as a Ajax request. We have specified the ControllerContext property of the controller with mocked object HTTPContextBase. Code Snippet controller.ControllerContext = new ControllerContext(         context.Object, new RouteData(), controller); Let me write a unit test for a normal HTTP method Code Snippet [Test] public void Index_NormalRequest_Returns_Index_With_Expense_List() {     // Arrange               Mock<HttpRequestBase> request = new Mock<HttpRequestBase>();     Mock<HttpResponseBase> response = new Mock<HttpResponseBase>();     Mock<HttpContextBase> context = new Mock<HttpContextBase>();       context.Setup(c => c.Request).Returns(request.Object);     context.Setup(c => c.Response).Returns(response.Object);       IEnumerable<Expense> fakeExpenses = GetMockExpenses();       expenseRepository.Setup(x => x.GetMany(It.         IsAny<Expression<Func<Expense, bool>>>())).         Returns(fakeExpenses);     ExpenseController controller = new ExpenseController(         commandBus.Object, categoryRepository.Object,         expenseRepository.Object);     controller.ControllerContext = new ControllerContext(         context.Object, new RouteData(), controller);     // Act     var result = controller.Index(null, null) as ViewResult;     // Assert     Assert.AreEqual("Index", result.ViewName);     Assert.IsNotNull(result, "View Result is null");     Assert.IsInstanceOf(typeof(IEnumerable<Expense>),             result.ViewData.Model, "Wrong View Model");     var expenses = result.ViewData.Model         as IEnumerable<Expense>;     Assert.AreEqual(3, expenses.Count(),         "Got wrong number of Categories"); }   In the above unit test, we are not specifying the XMLHttpRequest request header for Request object’s X-Requested-With, so that it will be normal HTTP Request. If this is a normal request, the action method will return a ViewResult with a view template named Index. The below is the implementation of Index action method Code Snippet public ActionResult Index(DateTime? startDate, DateTime? endDate) {     //If date is not passed, take current month's first and last date     DateTime dtNow;     dtNow = DateTime.Today;     if (!startDate.HasValue)     {         startDate = new DateTime(dtNow.Year, dtNow.Month, 1);         endDate = startDate.Value.AddMonths(1).AddDays(-1);     }     //take last date of start date's month, if end date is not passed     if (startDate.HasValue && !endDate.HasValue)     {         endDate = (new DateTime(startDate.Value.Year,             startDate.Value.Month, 1)).AddMonths(1).AddDays(-1);     }     var expenses = expenseRepository.GetMany(         exp => exp.Date >= startDate && exp.Date <= endDate);     //if request is Ajax will return partial view     if (Request.IsAjaxRequest())     {         return PartialView("_ExpenseList", expenses);     }     //set start date and end date to ViewBag dictionary     ViewBag.StartDate = startDate.Value.ToShortDateString();     ViewBag.EndDate = endDate.Value.ToShortDateString();     //if request is not ajax     return View("Index",expenses); }   The index action method will returns a PartialView named _ExpenseList, if it is an Ajax request and will returns a View named Index if it is a normal request. Source Code The source code has been taken from my EFMVC app which can download from here

    Read the article

  • Can data classes contain methods for validation?

    - by Arturas M
    OK, say I have a data class for a user: public class User { private String firstName; private String lastName; private long personCode; private Date birthDate; private Gender gender; private String email; private String password; Now let's say I want to validate email, whether names are not empty, whether birth date is in normal range, etc. Can I put that validation method in this class together with data? Or should it be in UserManager which in my case handles the lists of these users?

    Read the article

  • Cryptographic Validation Explained

    - by MarkPearl
    We have been using LogicNP’s CryptoLicensing for some of our software and I was battling to understand how exactly the whole process worked. I was sent the following document which really helped explain it – so if you ever use the same tool it is well worth a read. Licensing Basics LogicNP CryptoLicensing For .Net is the most advanced and state-of-the art licensing and copy protection system you can use for your software. LogicNP CryptoLicensing System uses the latest cryptographic technology to generate and validate licenses. The cryptographic algorithm used is the RSA algorithm which consists of a pair of keys called as the generation key and the validation key. Data encrypted using the generation key can only be decrypted using the corresponding validation key. How does cryptographic validation work? When a new license project is created, a unique validation-generation key pair is created for the project. When LogicNP CryptoLicensing For .Net generates licenses, it encrypts the license settings using the generation key. The validation key can be safely distributed with your software and is used during validation. During license validation, LogicNP CryptoLicensing For .Net attempts to decrypt the encrypted license code using the validation key. If the decryption is successful, this means that the data was encrypted using the generation key, since only the corresponding validation key can decrypt data encrypted with the generation key. This further means that not only is the license valid but that it was generated by you and only you since nobody else has access to the generation key. Generation Key This key is used by CryptoLicensing Generator to generate encrypted license codes. This key is stored in the license project file, so the license project file must be kept secure and confidential and must be accorded the same care as any other critical asset such as source code. Validation Key This key is used for validating generated license codes. It is the same key displayed in the 'Get Validation Key And Code' dialog (Ctrl+K) and is used by your software when validating license codes (using LogicNP.CryptoLicensing.dll). Unlike the generation key, it is not necessary to keep this key secure and confidential. Note that the generation key pair is stored in the project file created by LogicNP CryptoLicensing For .Net, so it is very important to backup this file and to keep it secure. Once the file is lost, it is not possible to retrieve the key pair. FAQ Do I use the same validation key to validate all license codes? Yes, the validation key (and generation key) for the project remains the same; you use the same key to validate all license codes generated using the project. You can retrieve the validation key using the "Project" menu --> "Get Validation Key & Code" menu item. Can license codes generated using generation key from one project be validated using validation key of another project? No! Q. Is every generated license code unique? A. Yes, every license code generated by CryptoLicensing is guaranteed to be unique, even if you generate thousands of codes at a time. Q. What makes CryptoLicensing so secure? A. CryptoLicensing uses the latest cryptographic technology to generate and validate licenses. The cryptographic algorithm used is the RSA asymmetric key algorithm which can use upto 3072-bit keys. Given current computing power, it takes years to break a 3072-bit key. Q. Is is possible for a hacker to develop a keygen for my software? A. Impossible. The cryptographic algorithm used by CryptoLicensing consists of a pair of keys called as the generation key and the validation key. Data encrypted with one key can only be decrypted by the other key and vice versa. Licenses are generated using the generation key and validated using the validation key. Without the generation key, it is impossible to generate valid licenses. Q. What is the difference between validation key and generation key? Generation Key This key is used by CryptoLicensing Generator to generate encrypted license codes. This key is stored in the license project file, so the license project file must be kept secure and confidential and must be accorded the same care as any other critical asset such as source code. Validation Key This key is used for validating generated license codes. It is the same key displayed in the 'Get Validation Key And Code' dialog (Ctrl+K) and is used by your software when validating license codes (using LogicNP.CryptoLicensing.dll). Unlike the generation key, it is not necessary to keep this key secure and confidential. Q. Do I have to include the license project file (.licproj) with my software? A. No!!! This goes against the very essence of the security of the asymmetric cryptographic scheme because the project file contains both the validation and generation key. With your software, you only need to include the validation key which will be used to validate licenses generated by CryptoLicensing using the generation key. The license project file should be treated as any other valuable and confidential asset such as your source code. Q. Does the license service need the license project file? A. Yes. The license project file is needed whenever new licenses are generated (via the UI, via the API or via the license service). As just one example, the license service generates new machine-locked licenses when activated licenses are presented to it for activation, therefore the license service needs the license project file. Q. Is it possible to embed my own data in the generated licenses? A. Yes. You can embed any amount of additional data in the licenses. This data will have the same amount of security as the license code itself and will be tamper-proof. The embedded user data can be retrieved from your software. Q. What additional steps can I take to ensure that my software does not get cracked? A. There are many methods and techniques which can make it extremely difficult for a hacker to crack your software. See Writing Effective License Checking Code And Designing Effective Licenses for more information. Q. Why is the license service not working? A. The most common cause is not setting the CryptoLicense.LicenseServiceURL property before trying to validate a license. Make sure that this property is set to the correct URL where your license service is hosted. The most common cause after this is that the license project file on the web server where your license service is hosted is not the latest. This happens if you make changes to the license project (for example, set the 'Enable With Serials' setting for a profile), but don't upload the updated project file to your web server. Q. Why are my serials not working? Serial codes require the user of a license service. See Using Serial Codes for more details. Also see the earlier question 'Why is the license service not working?' Q. Is the same validation key used to validate license codes generated from different profiles. A. Yes. Profiles are just pre specified license settings for quickly generating licenses having those settings. The actual license code is still generated using the license project's cryptographic generation key and thus, can be validated using the project's validation key. Q. Why are changes made to a profile not getting saved? A. Simply changing license settings via UI and saving the license project does not save those license settings to the active profile. You must first save the license settings to a profile using the Save/Save As command from the Profiles menu (see above). Q. Why is validation of activated licenses failing from CryptoLicensing Generator, but works from my software? A. Make sure that you have specified the URL of the license service using the Project Properties Dialog. Also see the earlier question 'Why is the license service not working?' Q. How can I extend the trial period of my customer? A. To extend the evaluation period of the customer, simply send him a new license code specifying the desired evaluation limits. Evaluation information such as the current used days, executions, etc are stored in garbled form in a registry location which is derived from the license code. Therefore, when a new license code is used, the old evaluation information will not be used and a new evaluation period will be started.

    Read the article

  • Yahoo sitemap validation

    - by Joel
    Hello, I am trying to submit sitemap.xml (index) to Yahoo Site Explorer but with no luck. I tried using website feed option in the site explorer to submit the sitemap, but I got validation errors. However, when submitting the same sitemap to google webmaster tools, the sitemap was validated successfully. Could it be for the fact that I am using sitemap with image tag: <image:image> <image:loc>http://www.domain.com/pic.jpg</image:loc> <image:title>picture</image:title> </image:image> When I tried validating the sitemap with inline tools such as http://www.xml-sitemaps.com/validate-xml-sitemap.html and http://www.w3.org/2001/03/webdata/xsv the error I received was: Attempt to load a schema document from http://www.google.com/schemas/sitemap-image/1.1 (source: new namespace) for http://www.google.com/schemas/sitemap-image/1.1, failed: Not recognised as W3C XML Schema or RDDL: html However, the declaration of the sitemap I use in the top of the document is the same as suggested by Google on their official page at http://www.google.com/support/webmasters/bin/answer.py?hl=en&answer=178636 : <?xml version="1.0" encoding="UTF-8"?> <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:image="http://www.google.com/schemas/sitemap-image/1.1"> <url> Any ideas how to resolve this issue? Thanks, Joel Thanks, Joel

    Read the article

  • php form-input validation

    - by fusion
    i have a html page in which i enter data which then submits and inserts in a database on a php page. how would i validate in php that the data received is not a duplicate of the data in the database? any help appreciated.

    Read the article

  • jQuery Validation Plugin: Validating Checkboxes with Different Names

    - by Michael
    I have a set of 4 checkboxes, all with different names, and require that at least 1 is checked. I know there are a few posts on here already trying to answer this question. The solution that seems to be most logical to me is the answer posted on Question 1734840, but I can't seem to get it working! What's wrong with my code? Or any other new coding ideas to get this working? I have set the class on all of them to 'require-one'. My jQuery code is $(document).ready(function(){ $("#itemForm").validate({ highlight: function(element, errorClass, validClass) { $(element).addClass(errorClass).removeClass(validClass); $(element.form).find("label[for=" + element.name + "]") .addClass("radioerror"); }, unhighlight: function(element, errorClass, validClass) { $(element).removeClass(errorClass).addClass(validClass); $(element.form).find("label[for=" + element.name + "]") .removeClass("radioerror"); }, rules: { 'require-one': { required : { depends: function(element) { var allBoxes = $('.require-one'); if (allBoxes.filter(':checked').length == 0) { if (allBoxes.eq(element).length != 0) { return true; } } return false; } } } , }, errorPlacement: function(error, element) { if ( element.is("#other_descrip") ) error.appendTo("#othererror" ); if ( element.is("#itemlist") ) error.appendTo("#itemerror" ); } }); });

    Read the article

  • ASP.NET MVC - Custom validation message for value types

    - by Giovanni Galbo
    When I use UpdateModel or TryUpdateModel, the MVC framework is smart enough to know if you are trying to pass in a null into a value type (e.g. the user forgets to fill out the required Birth Day field) . Unfortunately, I don't know how to override the default message, "A value is required." in the summary into something more meaningful ("Please enter in your Birth Day"). There has to be a way of doing this (without writing too much work-around code), but I can't find it. Any help? EDIT Also, I guess this would also be an issue for invalid conversions, e.g. BirthDay = "Hello".

    Read the article

  • email validation javascript

    - by fusion
    is this javascript function (checkValidity) correct? function checkTextBox(textBox) { if (!checkValidity(textBox.getValue())) displayError("Error title", "Error message", textBox); textBox.focus(); } function checkValidity(e) { var email; email = "/^[^@]+@[^@]+.[a-z]{2,}$/i"; if (!e.match(email)){ return false; else return true; } }

    Read the article

  • Zend framework currency validation

    - by Dan
    How can I validate (a form element in this case) to ensure that the value is a currency? Have looked at Zend_Validate_Float. Needs to check that value is between 0 and 2dp. Ideally locale-aware (as ZVF is) to allow for locale specific formatting (thousands, decimal as comma/dot) Would also want to extend to allow/disallow negative values And provide optional upper/lower limits. Is the key, as I can do 3. and 4. with a chain. Do I need regex?

    Read the article

< Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >