Search Results

Search found 296 results on 12 pages for 'validations'.

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

  • ruby-on-rails: update_attributes overrides model validations?

    - by cbrulak
    I have a typical, Post model: class Post< ActiveRecord::Base validates_presence_of :user_id #Line 1 validates_presence_of :title,:body #Line 2 in the controller, I have: def create if request.post? if login_required @post = Post.new(params[:post]) #Line 3 @post .update_attribute("user_id",session[:userid]) #Line 4 However, if the validations on Line 2 fail the Post will still be created, unless Line 4 is commented out. 1) Why? 2) Suggestions on a fix? Thanks

    Read the article

  • Jquery validations on form with no fields

    - by jcovert
    I have a table (in a form) populated with radio buttons (with a button for each value in a collection). If the collection is empty, nothing shows up in the table (which is fine). (I'm using Struts2) My trouble comes when validating that the user has selected one of these radio buttons when the submit button is clicked. I'm using JQUERY validations, and it works quite well UNLESS there are no radio buttons to select (collection is empty). $('#startProcessForm').validate({ rules: { selectedProcess: { required: true } }, messages: { selectedProcess: "Please select a process to start." } }); If the list IS empty, then there are no fields (radio button or otherwise) named "selectedProcess". So my question is this: How can I make "selectedProcess" exist AND fail the 'required:true' validation if there's nothing in the collection? I was thinking I could create an empty tag of the same name (selectedProcess) if the collection is empty? Here's what I'd guess would work but doesn't seem to: <s:if test="processes != null && !processes.isEmpty()"> <s:iterator value="processes" status="processesStatus"> <tr> <td><s:radio name="selectedProcess" list="{name}"></s:radio></td> </tr> </s:iterator> </s:if> <s:else> <tr> <td><a name="selectedProcess"></a></td> </tr> </s:else> Thanks!

    Read the article

  • Dynamically changing validations in Rails

    - by user94154
    I have a model with a validation. At runtime, I'd like to change a value of the validation. For example: in the model bid.rb: class Bid ActiveRecord::Base @foo = Foo.find(1) validates_inclusion_of :amt, :in => [email protected], :message => "must be between 1 and #{@foo.bar}" end and in the application_controller (pseudocode): if today == 'wednesday' Foo.update(1, :bar => 10) else Foo.update(1, :bar => 5) end However, this setup isn't working. The "foo" attribute never updates. It seems that the validation code is set only when the dev server starts and then doesn't change.

    Read the article

  • Do validations still fire in ASP.NET even if the controls are hidden?

    - by Josh
    I have a form that uses ASP.NET validations. I am using some inline C# in the aspx to show/hide certain controls depending on a user's role. I would use the Visible property, but there are so many of them, I just decided to do inline C# to show and hide (I know, not best practice, but bear with me for a second). I am having an issue where Page.IsValid is always set to False when I submit my form (when certain fields are being hidden). Will the validations still fire off even if the controls are not even rendered on the pag? Also, if this is not the case, is there an effective way of breaking down Page.IsValid to find out what is setting it to False? Thanks.

    Read the article

  • Constructor vs setter validations

    - by Jimmy
    I have the following class : public class Project { private int id; private String name; public Project(int id, String name, Date creationDate, int fps, List<String> frames) { if(name == null ){ throw new NullPointerException("Name can't be null"); } if(id == 0 ){ throw new IllegalArgumentException("id can't be zero"); } this.name = name; this.id = id; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } } I have three questions: Do I use the class setters instead of setting the fields directly. One of the reason that I set it directly, is that in the code the setters are not final and they could be overridden. If the right way is to set it directly and I want to make sure that the name filed is not null always. Should I provide two checks, one in the constructor and one in the setter. I read in effective java that I should use NullPointerException for null parameters. Should I use IllegalArgumentException for other checks, like id in the example.

    Read the article

  • Firing server side validations on moving from one page to another in Asp.NEt

    - by Sumeru Suresh
    I need to fire certain server side validation for a page when the user is trying move from that page to another.. Even though he is not clicking on any buttons these server side validations have to be fired when he is moving out of this page.. Could you please help me how to handle this.. Required field validations will not happen as the user is entering the page and leaving the page without doing any action in the page..

    Read the article

  • Credit Card checksums and validations that do not require connection to the financial institution

    - by cjavapro
    The validations I know of are: Checksum the whole card number should add up to zero. (range is 0-9) Check the first digit(s) against the card type Check the length against the card type Check the CCV length against the card type (I think all the major types are 3 anyway) Of course make sure it is accepted card type as well as non expired. Are there any other validations :) (I expect many folks did not know about all of these) The reason I ask is because I overheard there was one to checksum number against expiration or CCV.. I just wanted to check.

    Read the article

  • Adding validations without knowing the fields

    - by Frexuz
    My example form <% form_for @ad do |f| %> <%= f.error_messages %> <p> <%= f.label :ad_type_id %><br /> <%= f.collection_select(:ad_type_id, AdType.all, :id, :name) %> </p> <p> <% @ad.ad_properties.each do |property| %> <%= property.name %>: <% f.fields_for :ad_values do |value_field| %> <%= value_field.text_field :ad_id, :value => @ad.id %> <%= value_field.text_field :ad_property_id, :value => property.id %> <%= value_field.text_field :value %> <% end %><br /><br /> <% end %> </p> <p> <%= f.label :description %><br /> <%= f.text_area :description %> </p> <p><%= f.submit %></p> <% end %> Explanation: Ad has many properties. I can add new properties at any time (it's a normal model). Lets say the Ad is of the type 'hotel'. Then I would add properties like 'stars' and 'breakfast_included' Then I store each of these properties' values in a separate model. And all this works fine with my form above. My problem: These fields are not validated because I can't know what their names are. I need to add validations dynamically somehow. My thought: #Before the normal validations kick in def add_validations self.properties.each do |property| property.add_validation :whatever #somehow :) end end How could I do this?

    Read the article

  • Active Record Validations : uniqueness of

    - by Elliot
    Hey guys, I'm using http://ar.rubyonrails.org/classes/ActiveRecord/Validations/ClassMethods.html#M000086 to validate records. My form is currently a remote form, using RJS. My question, is how to I return the :message (for errors) to the page through ajax (and I assume the create.rjs file)? Best, Elliot

    Read the article

  • Can we use spring FTL based form validations with any controller other than SimpleFormController

    - by Adhir Aima
    Hi, Because of some design specification we have to extend all controllers in spring MVC from a class that extends AbstractCommandController. I am trying to include the spring FTL based form validations in my FTL file, but it gives me an error like Method public org.springframework.web.servlet.support.BindStatus org.springframework.web.servlet.support.RequestContext.getBindStatus(java.lang.String) throws java.lang.IllegalStateException threw an exception when invoked on org.springframework.web.servlet.support.RequestContext@b05cd7 with arguments of types [java.lang.String,] The problematic instruction: == assignment: status=springMacroRequestContext.getBindStatus(path) [on line 120, column 9 in spring.ftl] in user-directive spring.bind [on line 47, column 33 in myProfile.ftl] Java backtrace for programmers: freemarker.template.TemplateModelException: Method public org.springframework.web.servlet.support.BindStatus org.springframework.web.servlet.support.RequestContext.getBindStatus(java.lang.String) throws java.lang.IllegalStateException threw an exception when invoked on org.springframework.web.servlet.support.RequestContext@b05cd7 with arguments of types [java.lang.String,] I have put the command name properly in the controller class and in the controller class, neither the specified name nor the default "command" works. Some help please. And would be much appreciated if it comes with an example. Thanks in advance, Adhir Aima

    Read the article

  • Two models, one STI and a Validation

    - by keruilin
    Let's say I have two tables -- Products and Orders. For the sake of simplicity assume that only one product can be purchased at a time so there is no join table like order_items. So the relationship is that Product has many orders, and Order belongs to product. Therefore, product_id is a fk in the Order table. The product table is STI -- with the subclasses being A, B, C. When the user orders subclass Product C, two special validations must be checked on the Order model fields order_details and order_status. These two fields can be nil for all other Product subclasses (ie A and B). In other words, no validation needs to run for these two fields when a user purchases A and B. My question is: How do I write validations (perhaps custom?) in the Order model so that the Order model knows to only run the validations for the two fields -- order_details and order_status -- when Product subclass C is being saved to the orders table?

    Read the article

  • Regex help in java validations

    - by user1697113
    Hi i want to do some validations.I used to put regex in JS but im new to regex in java, so i tried to make up a code on similar lines in java. Here is what i did. 1)Check whether first character in string is alphanumeric. 2)Check whether the string atleast 1 number. so i wrote a code, but it is always returning false.I am not sure if i'm doing this correctly. private static boolean checkEmbeddedPassword(final String field) { boolean returnValue=true; String testpatternAlpha="/^[A-Za-z0-9].+$/"; String testNumber="/[0-9]/"; Pattern pattern=Pattern.compile(testpatternAlpha); Pattern pattern2=Pattern.compile(testNumber); Matcher matcher = pattern.matcher(field); Matcher matcher2 = pattern2.matcher(field); boolean firstChar=matcher.matches(); boolean numberFlag=matcher2.matches(); System.out.println("-----the value of pwd iss-----"+field); System.out.println("---------Regex---------Out--put-----"+firstChar); System.out.println("---------Regex---------Out- for numeral-put-----"+numberFlag); if(firstChar){ returnValue=false; } else if(field.contains(" ")) { System.out.println("-----------cannot have space------"); returnValue=false; } else if(numberFlag) { returnValue=false; } return returnValue; }

    Read the article

  • Textbox time validations (javascript)

    - by unos
    I have a textbox in which user can enter time (eg- 01:00) and also a drop down box for entering AM/PM fields. (Since the AM/PM field is used, 12-hour time format is used.) The text box allows a max entry of 5 chars only (eg - 01:00). Pls let me know how I can set the 3rd char as a default -colon : , so that the user simply has to enter only the time. How to check if the time entered by the user is numeric or not?. Autocompletion feature : for eg, if user enters 1 then it would automatically be set to 01:00 Javascript Validations for 12-hour format. Eg: if user enters 13:00 then it should change to 01:00 How can I append the text box time values with the am/pm value selected in the drop down box?. Once the values are appended, automatically populate another text box (text box 2) with the result. Eg: 01:00 + pm should be set as 01:00p in the new text box (text box 2). Any help would be appreciated.

    Read the article

  • Improving performance on data pasting 2000 rows with validations

    - by Lohit
    I have N rows (which could be nothing less than 1000) on an excel spreadsheet. And in this sheet our project has 150 columns like this: Now, our application needs data to be copied (using normal Ctrl+C) and pasted (using Ctrl+V) from the excel file sheet on our GUI sheet. Copy pasting 1000 records takes around 5-6 seconds which is okay for our requirement, but the problem is when we need to make sure the data entered is valid. So we have to validate data in each row generate appropriate error messages and format the data as per requirement. So we need to at runtime parse and evaluate data in each row. Now all the formatting of data and validations come from the back-end database and we have it in a data-table (dtValidateAndFormatConditions). The conditions would be around 50. So you can see how slow this whole process becomes since N X 150 X 50 operations are required to complete this whole process. Initially it took approximately 2-3 minutes but now i have reduced it to 20 - 30 seconds. However i have increased the speed by making an expression parser of my own - and not by any algorithm, is there any other way i can improve performance, by using Divide and Conquer or some other mechanism. Currently i am not really sure how to go about this. Here is what part of my code looks like: public virtual void ValidateAndFormatOnCopyPaste(DataTable DtCopied, int CurRow) { foreach (DataRow dRow in dtValidateAndFormatConditions.Rows) { string Condition = dRow["Condition"]; string FormatValue = Value = dRow["Value"]; GetValidatedFormattedData(DtCopied,ref Condition, ref FormatValue ,iRowIndex); Condition = Parse(Condition); dRow["Condition"] = Condition; FormatValue = Parse(FormatValue ); dRow["Value"] = FormatValue; } } The above code gets called row-wise like this: public override void ValidateAndFormat(DataTable dtChangedRecords, CellRange cr) { int iRowStart = cr.Row, iRowEnd = cr.Row + cr.RowCount; for (int iRow = iRowStart; iRow < iRowEnd; iRow++) { ValidateAndFormatOnCopyPaste(dtChangedRecords,iRow); } } Please know my question needs a more algorithmic solution than code optimization, however any answers containing code related optimizations will be appreciated as well. (Tagged Linq because although not seen i have been using linq in some parts of my code).

    Read the article

  • jQuery validations not working in IE 7?

    - by Pselus
    I have a problem. The client is claiming that a prize signup form I built for them is not working in IE 7. It works in IE 8 just fine which they agree about, but in IE 7 it doesn't. (luckily they don't care about IE 6). I was hoping someone could help me debug it since I don't have access to a machine with IE 7 (I work on a Mac). The page is here: http://www.fuchscorp.com/midamerica/prizes/prize.signup.php When you click the Submit button in IE 7 it just doesn't work. Don't worry about submitting information as the site isn't live (so, no...you won't be winning any prizes). If someone could please help me debug this and figure out what's going on that would be amazingly helpful.

    Read the article

  • Certificates Validations Issues

    - by user298331
    Hi All, i am facing some issues related certificates.i need some help to resolve these issues. Requirements : security mode="TransportWithMessageCredential" binding binding name="basicHttpEndpointBinding" certificateValidationMode ="ChainTrust" revocationMode="Online" Certificates : Service Cerificates : Transportlevel : XXXX.cer my cerificate name is my system DNS name and it is having root node i.e RootTrnCA.cer this is used to enable https.but am not validationg transport level certificates. Message Level : services.ca.iim (VXXXX.Cer--Act.Mac.Ca--services.ca.iim ) Client Cerificates : Transportlevel : ZZZZ.cer my cerificate name is my system DNS name and it is having root node i.e RootTrnCA.cer ignoring transport certificate errors through coading..... Message Level : client.ca.iim (VXXXX.Cer--Act.Mac.Ca--client.ca.iim ) Issues : 1) Response message is not contain Service certificate Signature in Soap header.so i am not able to validate Server certificate details in Client code. 2)if i use the transport with message credential and Chaintrust.i am getting error : The revocation function was unable to check revocation because the revocation server was offline.) so please very the below service and cleint config and correct me if i am wrong. Service config : Client config : i am attaching certificate through coading : objProxy.ChannelFactory.Credentials.ClientCertificate.SetCertificate(System.Security.Cryptography.X509Certificates. StoreLocation.LocalMachine, System.Security.Cryptography.X509Certificates. StoreName.My, X509FindType.FindBySubjectName, "client.ca.iim"); <binding name="XXXXXServiceHost.Http" closeTimeout="00:01:00" openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00" allowCookies="false" bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard" maxBufferSize="65536" maxBufferPoolSize="524288" maxReceivedMessageSize="65536" messageEncoding="Text" textEncoding="utf-8" transferMode="Buffered" useDefaultWebProxy="true"> <readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384" maxBytesPerRead="4096" maxNameTableCharCount="16384" /> <security mode="TransportWithMessageCredential"> <transport clientCredentialType="None" proxyCredentialType="None" realm="" /> <message clientCredentialType="Certificate" algorithmSuite="Default" /> </security> </binding> </basicHttpBinding> </bindings> <client> <endpoint address="https://XXXXXX/XXXServiceHost/MemberSvc.svc/soap11" binding="basicHttpBinding" bindingConfiguration="XXXServiceHost.Http" contract="ServiceReference1.IMemberIBA" name="XXXServiceHost.Http" /> </client> </system.serviceModel>Please Verify both and Help me how to resolve above two issues . Thanks Babu

    Read the article

  • floating point precision in ruby on rails model validations

    - by Chris Allison
    Hello I am trying to validate a dollar amount using a regex: ^[0-9]+\.[0-9]{2}$ This works fine, but whenever a user submits the form and the dollar amount ends in 0(zero), ruby(or rails?) chops the 0 off. So 500.00 turns into 500.0 thus failing the regex validation. Is there any way to make ruby/rails keep the format entered by the user, regardless of trailing zeros?

    Read the article

  • ASP.NET MVC Validations

    - by Pinu
    I need to validate the Advanced search form , but it has data to be sent to 2 different table people and documents so i am unable to use data annotations. I need to validate the Name to be characters only, account number & amount to be a number.How can i validate these fields? <asp:Content ID="indexContent" ContentPlaceHolderID="MainContent" runat="server"> <center> <img src="../../Content/images/DocuVault_Logo.png" alt="DocuVault" /> <%= Html.ValidationSummary() %> <% using (Html.BeginForm("QuickSearch", "Search")) { %> <div id="div_QuickSearch"> <table> <tr> <td colspan="2"> <%= Html.TextBox("search", "", new { style = "width: 300px" })%> <input type="submit" value="Search" /> </td> </tr> <tr> <td colspan="2"> <%= Html.ValidationMessage("search") %> </td> </tr> <tr> <td><a href="#" id="link_advanced">Advanced Search</a></td> </tr> </table> <br /> </div> <% } %> <ul> </ul> </div> <% using (Html.BeginForm("AdvancedSearch", "Search")) { %> <div id="div_AdvancedSearch" style="display: none; width: 420px; padding: 10px;"> People <table style="border: solid 1px black; padding: 5px; width: 400px;"> <tr> <td>Name:</td> <td align="right"> <%= Html.TextBox("searchName") %> <%= Html.ValidationMessage("searchName")%> </td> </tr> <tr> <td>Address:</td> <td align="right"> <%= Html.TextBox("searchAddress") %> <%= Html.ValidationMessage("searchAddress")%> </td> </tr> <tr> <td>Account Number:</td> <td align="right"> <%= Html.TextBox("searchAccountNumber") %> <%= Html.ValidationMessage("searchAccountNumber")%> </td> </tr> </table> <br /> Documents <table style="border: solid 1px black; padding: 5px; width: 400px;"> <tr> <td>Invoice:</td> <td align="right"> <%= Html.TextBox("searchInvoice") %> <%= Html.ValidationMessage("searchInvoice")%> </td> </tr> <tr> <td>Amount:</td> <td align="right"> <%= Html.TextBox("searchAmount") %> <%= Html.ValidationMessage("searchAmount")%> </td> </tr> <tr> <td>Job:</td> <td align="right"> <%= Html.TextBox("searchJob") %> <%= Html.ValidationMessage("searchJob")%> </td> </tr> <tr> <td>SDI:</td> <td align="right"> <%= Html.TextBox("searchSDI") %> <%= Html.ValidationMessage("searchSDI")%> </td> </tr> <tr> <td>Date:</td> <td align="right"> <%= Html.TextBox("searchDateBegin", "", new { style = "width: 88px" })%> to <%= Html.TextBox("searchDateEnd", "", new { style = "width: 88px" })%> <%= Html.ValidationMessage("searchDate")%> </td> </tr> </table> <br /> <div style="width: 100%;"> <span style="float: left; margin-left: 10px;"><a href="#" id="link_quick">QuickSearch</a></span> <span style="float: right; margin-right: 10px;"><input type="submit" value="Advanced Search" /></span> </div> </div> <% } %> </center> </asp:Content>

    Read the article

  • Rails 3: Validate combined values

    - by Cimm
    In Rails 2.x you can use validations to make sure you have a unique combined value like this: validates_uniqueness_of :husband, :scope => :wife In the corresponding migration it could look like this: add_index :family, [:husband, :wife], :unique => true This would make sure the husband/wife combination is unique in the database. Now, in Rails 3 the validation syntax changed and the scope attribute seems to be gone. It now looks like: validates :husband, :presence => true Any idea how I can achieve the combined validation in Rails 3? The Rails 2.x validations still work in Rails 3 so I can still use the first example but it looks so "old", are there better ways?

    Read the article

  • Validations for a has_many/belongs_to relationship

    - by Craig Walker
    I have a Recipe model which has_many Ingredients (which in turn belongs_to Recipe). I want Ingredient to be existent dependent on Recipe; an Ingredient should never exist without a Recipe. I'm trying to enforce the presence of a valid Recipe ID in the Ingredient. I've been doing this with a validates :recipe, :presence => true (Rails 3) statement in Ingredient. This works fine if I save the Recipe before adding an Ingredient to it's ingredients collection. However, if I don't have explicit control over the saving (such as when I'm creating a Recipe and its Ingredients from a nested form) then I get an error: Ingredients recipe can't be blank I can get around this simply by dropping the presence validation on Ingredient.recipe. However, I don't particularly like this, as it means I'm working without a safety net. What is the best way to enforce existence-dependence in Rails? Things I'm considering (please comment on the wisdom of each): Adding a not-null constraint on the ingredients.recipe_id database column, and letting the database do the checking for me. A custom validation that somehow checks whether the Ingredient is in an unsaved recipe's ingredient collection (and thus can't have a recipe_id but is still considered valid).

    Read the article

  • validations in XML

    - by charan
    hi all.. i have a address.java file with a textField as PostCode. in that only number should accepted. if i try to enter characters in that it sould popup a message. these validation must be done in address.xml file only i tried by giving the validation as <testcase> <messageType>error</messageType> <validationType>isDigit</validationType> <validationRule>5</validationRule> </testcase> but its not working. plz anybody can help me in solving this

    Read the article

  • ActiveRecord Validations for Models with has_many, belongs_to associations and STI

    - by keruilin
    I have four models: User Award Badge GameWeek The associations are as follows: User has many awards. Award belongs to user. Badge has many awards. Award belongs to badge. User has many game_weeks. GameWeek belongs to user. GameWeek has many awards. Award belongs to game_week. Thus, user_id, badge_id and game_week_id are foreign keys in awards table. Badge implements an STI model. Let's just say it has the following subclasses: BadgeA and BadgeB. Some rules to note: The game_week_id fk can be nil for BadgeA, but can't be nil for BadgeB. Here are my questions: For BadgeA, how do I write a validation that it can only be awarded one time? That is, the user can't have more than one -- ever. For BadgeB, how do I write a validation that it can only be awarded one time per game week?

    Read the article

  • Extending a form field to add new validations.

    - by duallain
    I've written an app that uses forms to collect information that is then sent in an email. Many of these forms have a filefield used to attach files to the email. I'd like to validate two things, the size of the file (to ensure the emails are accepted by our mail server. I'd also like to check the file extension, to discourage attaching file types not useable for our users. (This is the python class I'm trying to extend) class FileField(Field): widget = FileInput default_error_messages = { 'invalid': _(u"No file was submitted. Check the encoding type on the form."), 'missing': _(u"No file was submitted."), 'empty': _(u"The submitted file is empty."), 'max_length': _(u'Ensure this filename has at most %(max)d characters (it has %(length)d).'), } def __init__(self, *args, **kwargs): self.max_length = kwargs.pop('max_length', None) super(FileField, self).__init__(*args, **kwargs) def clean(self, data, initial=None): super(FileField, self).clean(initial or data) if not self.required and data in EMPTY_VALUES: return None elif not data and initial: return initial # UploadedFile objects should have name and size attributes. try: file_name = data.name file_size = data.size except AttributeError: raise ValidationError(self.error_messages['invalid']) if self.max_length is not None and len(file_name) > self.max_length: error_values = {'max': self.max_length, 'length': len(file_name)} raise ValidationError(self.error_messages['max_length'] % error_values) if not file_name: raise ValidationError(self.error_messages['invalid']) if not file_size: raise ValidationError(self.error_messages['empty']) return data

    Read the article

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