Search Results

Search found 7702 results on 309 pages for 'django validation'.

Page 66/309 | < Previous Page | 62 63 64 65 66 67 68 69 70 71 72 73  | Next Page >

  • How To Share Information Between Django and Javascript?

    - by Randy
    So I am pretty new to both Django and Javascript (I am using JQuery) and I am wondering if I am doing a hack or if there are more slick ways to send client-side displayed database ids to the django server-side. Here is my process: I have a dataTable (http://datatables.net) that I am displaying rows of data by using the bProcessing option to use AJAX to retrieve records from the database. The URL in my urls.py is something like: url(r'^assets/activitylog/(?P<cid>.*)$', views.getActivityTable_ajax, name="activitylog_table"), and my dataTable ajax-relavant code is something like: "sAjaxSource": "/assets/activitylog/" + getIDFromHTML(), where the javascript function getIDFromHTML() grabs <cid> that is used by the Django view is simply: function getIDFromHTML(){ // Simply return the text in the #release_id div element from the HTML return $("#release_id").html(); }; This is the part that seems "hacky" to me. I am inserting into my template code the database id that I am using in the datatables URL (with display:none in the css) just so I can pass it back to the view. Most of this is necessitated because one cannot use django template tags in the javascript code unless the code is embedded into the HTML itself, which I am not (and will not) do. The only other thing that I have found is to change the URL to get rid of the parameter passed in to: url(r'^assets/activitylog', views.getActivityTable_ajax, name="activitylog_table"), and change the view code to: def getActivityTable_ajax(request): """Returns the activity for a given pid from HTTP GET ajax reqest""" pid = int(urlparse.urlparse(request.META['HTTP_REFERER']).path.split('/')[-1]) # rest of view code here... since the id that I need is on the end of this referer url. This way I don't have to monkey around with embedding the hidden database id into the HTML and passing it back to via ajax the the table population view code. Is it okay to use HTTP_REFERER in the request object in this manner? Am I going about this in the totally wrong way? Thanks in advance!

    Read the article

  • Validation problem with a 'JotForm' template

    - by Thomas
    A client sent me a form template they had created using jotform.com to implement on their wordpress site. The form template is supposed to hide part of the form until the user clicks the 'next' button. At which point a script is supposed to validate all of the input fields the user has presumably filled out and then display the rest of the form. While I have successfully managed to get the form to display the next part of the form when the user clicks 'next', it fails to validate the input fields. Its kind of difficult to explain without a huge block of text so it is probably easier to show you: The original working template that the customer sent me: http://www.loftist.com/jotform/List_Your_Loft.html The problem child: http://www.loftist.com/?page_id=78 If you just click on one of the input fields and then click elsewhere on the page, the input fields successfully return a validation error message and prevent the user from clicking on the 'next' button. However, if you simply click on the next button than the next set of fields get displayed. Any thoughts? What am I doing wrong here? Im convinced this must be a really simple problem but Im not sure what it could be....

    Read the article

  • django-cms lighttpd redirect domain to url

    - by Robert
    Hello, I am using djano-cms for my site, but instead of language alias /en/ /de/ I need to use another domain. I would like to avoid running multiple django instances, and instead I would like to use lighttpd redirects if possible. I would like requests coming to domain2.com getting data from domain.com/en . The best would be if the user entering: domain2.com/offer got transparently data from domain.com/en/offer Tried many solutions with url.redirect, url.rewrite but none seems to work as desired. Also tried with: http://stackoverflow.com/questions/261904/matching-domains-with-regex-for-lighttpd-mod-evhost-www-domain-com-domain-com but that didn't work. Please help. This is my lighttpd configuration. $HTTP["host"] == "^domain2\.com" { url.redirect = ("^/(.*)" => "http://domain.com/en/$1") } $HTTP["host"] =~ "^domain\.com" { server.document-root = "/var/www/django/projects/domain/" accesslog.filename = "/var/log/lighttpd/domain.log-access.log" server.errorlog = "/var/log/lighttpd/www.domain-error.log" fastcgi.server = ( "/domain-service.fcgi" => ( "main" => ( "socket" => "/tmp/django-domain.sock", "check-local" => "disable", ) ), ) alias.url = ( "/media/" => "/var/www/django/projects/domain/media/", ) url.rewrite-once = ( "^(/site_media.*)$" => "$1", "^(/media.*)$" => "$1", "^/favicon\.ico$" => "/media/favicon.ico", "^(/.*)$" => "/domain-service.fcgi$1", } Thanks

    Read the article

  • Using Memcached in Python/Django - questions.

    - by Thomas
    I am starting use Memcached to make my website faster. For constant data in my database I use this: from django.core.cache import cache cache_key = 'regions' regions = cache.get(cache_key) if result is None: """Not Found in Cache""" regions = Regions.objects.all() cache.set(cache_key, regions, 2592000) #(2592000sekund = 30 dni) return regions For seldom changed data I use signals: from django.core.cache import cache from django.db.models import signals def nuke_social_network_cache(self, instance, **kwargs): cache_key = 'networks_for_%s' % (self.instance.user_id,) cache.delete(cache_key) signals.post_save.connect(nuke_social_network_cache, sender=SocialNetworkProfile) signals.post_delete.connect(nuke_social_network_cache, sender=SocialNetworkProfile) Is it correct way? I installed django-memcached-0.1.2, which show me: Memcached Server Stats Server Keys Hits Gets Hit_Rate Traffic_In Traffic_Out Usage Uptime 127.0.0.1 15 220 276 79% 83.1 KB 364.1 KB 18.4 KB 22:21:25 Can sombody explain what columns means? And last question. I have templates where I am getting much records from a few table (relationships). So in my view I get records from one table and in templates show it and related info from others. Generating page last a few seconds for very small table (<100records). Is it some easy way to cache queries from templates? Have I to do some big structure in my view (with all related tables), cache it and send to template?

    Read the article

  • jQuery Form Validation being bypassed

    - by user1953681
    Can someone tell me what is wrong with my jQuery validation? It is not validating my form, rather, just ignoring the code resulting in no check of the inputs. Form: <form class="form" accept-charset="UTF-8" action="URL-to-complete-form" method="POST" onsubmit="return validateForm();"> <input class="form-name" type="text" placeholder="Name"></div> <input class="form-email" type="text"placeholder="Email"></div> <input style="background-color: #fc8f12;" type="submit" value="Subscribe"> </div> </form> Javascript: function validateForm() { // Validate Name var title = $(".form-name").val(); if (title=="" ||title=="Name" || title==null) { } else { alert("Please enter a name!"); } // Validate Email var email = $(".form-email").val(); if ((/(.+)@(.+){2,}\.(.+){2,}/.test(email)) || email=="" || email=="Email" || email==null) { } else { alert("Please enter a valid email"); } return false; } Thank you all for your time and help.

    Read the article

  • IP Address Validation Help

    - by Zubair1
    I am using this IP Validation Function that I came across while browsing, it has been working well until today i ran into a problem. For some reason the function won't validate this IP as valid: 203.81.192.26 I'm not too great with regular expressions, so would appreciate any help on what could be wrong. If you have another function, I would appreciate if you could post that for me. The code for the function is below: public static function validateIpAddress($ip_addr) { global $errors; $preg = '#^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}' . '(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$#'; if(preg_match($preg, $ip_addr)) { //now all the intger values are separated $parts = explode(".", $ip_addr); //now we need to check each part can range from 0-255 foreach($parts as $ip_parts) { if(intval($ip_parts) > 255 || intval($ip_parts) < 0) { $errors[] = "ip address is not valid."; return false; } return true; } return true; } else { $errors[] = "please double check the ip address."; return false; } }

    Read the article

  • Load page for validation but do not display it to user in ASP.NET

    - by Kevin
    We have a site requiring users pay $2 to view the details of a record. We occasionally get complaints because we send them to the payment page, and once they pay it turns out the record isn't valid, or it was lost, or the data couldn't be generated. So we want to add in a check to ensure the page constructs properly before the user is required to pay for it. However, we don't want the user to have access to the page until they pay for it. Is there anything in ASP.NET 3.5 or just general web design that would allow something like this? The data on the record is real time and computed on a backend server before sent to the client. Occasionally this computation fails for whatever reason. Our alternative is to call all of the loading methods and validate the data, then redirect them to the payment page. The problem is A) this will be a relatively involved process rewriting all of these methods to return validation information, and B) it still doesn't guarentee us the page will load properly. Any thoughts?

    Read the article

  • How to pass a value from the Jquery validation

    - by user2963960
    How can i pass a value from the jquery validation. I have an input box named clubCardNumber it should validate the length of the inputted value. If the length is equal to 10 the value passes to the hidden field named else validated it if its null or empty if all validations are true then its a clubCard. Here is how i implemented it on Javascript function validateClubCardNumber() { var varClubCardNumber = $('#clubCardNumber').val(); $('#phoneNumber').val(""); var returnVal = true; if ((null == varClubCardNumber || '' == trim(varClubCardNumber)){ return false; } if( varClubCardNumber.length < 10 ){ return false; }else if( varClubCardNumber.length == 10 ) { //The Phone Number field should contains numbers only var pattern = /^[0-9 -]*$/ ; var flag = pattern.test(trim(varClubCardNumber)); if(flag == false){ return false; }else{ $('#phoneNumber').val(varClubCardNumber); returnVal = true; } } } return returnVal; } HTML <div > <label for="clubCardNumber" >Card or Phone Number:</label> <input id="clubCardNumber" name="clubCardNumber" type="text" placeholder="Card or Phone Number" value="" maxlength="20"/> </div> <input type="hidden" id="phoneNumber" name="phoneNumber" value=""/>

    Read the article

  • CodeIgniter - Image Validation & Thumbnailing

    - by Sebhael
    I'm currently trying to create a function that validates and creates thumbnails for images on upload - but I'm quite lost on what I'm doing. I'm assuming I'm off on my terminology so I'm not really getting any search results to help point me in the right direction. My playground is a form with 6 upload fields that are required. One of these fields is for a simple 32x32 icon image, another a portrait orientation (most likely) photo, and then 4 standard desktop screenshots -- and I'm using CodeIgniter as my framework. I would like to create a function that validates/thumbnails images, and only have to call it on the validation if at all possible. I know I can achieve this per-image, since the documentation for CI is quite through on this - but to reduce redundancy I'm looking for the better option. Outside of that, I don't even actually understand in full how to manipulate images unless it's just $this-input-post('field') - then calling all functions onto this? I don't know, I'm confused and posting on the actual CI forums has yielded me nothing - so all I'm really looking for is a point in the right direction to understanding what I'm trying to achieve here. This also all might not make any sense, I know it doesn't to me - but I can explain more if needed. Thanks in advance.

    Read the article

  • MVC + Is validation attributes enough?

    - by ebb
    My ViewModel has validation attributes that ensure that it wont be empty etc. - Is that enough or should I let my the code contracts I have made be in the ActionResult too? Example: // CreateCaseViewModel.cs public class CreateCaseViewModel { [Required] public string Topic { get; set; } [Required] public string Message { get; set; } } // CaseController.cs [AuthWhere(AuthorizeRole.Developer)] [HttpPost] public ActionResult Create(CreateCaseViewModel model) { if(!ModelState.IsValid) { // TODO: some cool stuff? } if (string.IsNullOrWhiteSpace(model.Message)) { throw new ArgumentException("Message cannot be null or empty", model.Message); } if (string.IsNullOrWhiteSpace(model.Topic)) { throw new ArgumentException("Topic cannot be null or empty", model.Topic); } var success = false; string message; var userId = new Guid(_membershipService.GetUserByUserName(User.Identity.Name).ProviderUserKey.ToString()); if(userId == Guid.Empty) { throw new ArgumentException("UserId cannot be empty"); } Case createCase = _caseService.CreateCase(model.Topic, model.Message); if(createCase == null) { throw new ArgumentException("Case cannot be null"); } if(_caseService.AddCase(createCase, userId)) { message = ControllerResources.CaseCreateFail; } else { success = true; message = ControllerResources.CaseCreateSuccess; } return Json(new { Success = success, Message = message, Partial = RenderPartialViewToString(ListView, GetCases) }); }

    Read the article

  • End-date greater than start-date validation javascript not working properly

    - by ianco slovak
    I am trying to make a validation for my dates so that enddate to be greater than start date but is not working.What am i doing wrong? <head> <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> <link href="@Url.Content("~/Content/Site.css")" rel="stylesheet" type="text/css" /> <script src="@Url.Content("~/Scripts/jquery-ui-1.8.19.min.js")" type="text/javascript"></script> <script src="@Url.Content("~/Scripts/jquery-ui.unobtrusive.min.js")" type="text/javascript"></script> <script src="@Url.Content("~/Scripts/jquery-ui.unobtrusive-0.5.0.min.js")" type="text/javascript"></script> <script src="@Url.Content("~/Scripts/gen_validatorv4.js")" type="text/javascript"></script> </head> @using (Html.BeginForm("SearchFree", "Reservation", FormMethod.Get,new {id = "form" })) { <h7>Introduceti perioada Rezervarii</h7> <div class="editor-label"> <label id="cautare" for="StartDate">Data Intrare: </label>@(Html.JQueryUI().Datepicker("StartDate").DateFormat("mm-dd-yy").MinDate(DateTime.Today).ShowButtonPanel(true).ChangeYear(true).ChangeMonth(true).NumberOfMonths(2)) </div> <div class="editor-label"> <label id="cautare" for="EndDate">Data Iesire:</label>@(Html.JQueryUI().Datepicker("EndDate").DateFormat("mm-dd-yy").MinDate(DateTime.Today).ShowButtonPanel(true).ChangeYear(true).ChangeMonth(true).NumberOfMonths(2)) </div> <p> <input id="buton1" type="submit" value="Cauta camere libere" /> </p> } <script type="text/javascript"> $(document).ready(function () { $.validator.addMethod("EndDate", function (value, element) { var startDate = $('.StartDate').val(); return Date.parse(startDate) <= Date.parse(value); } , "* End date must be after start date"); $('.form').validate(); }); </script>

    Read the article

  • Generic validate input data via regex. Input error when match.count == 0

    - by Valamas
    Hi, I have a number of types of data fields on an input form, for example, a web page. Some fields are like, must be an email address, must be a number, must be a number between, must have certain characters. Basically, the list is undefinable. I wish to come up with a generic way of validating the data inputed. I thought I would use regex to validate the data. The fields which need validation would be related to a "regex expression" and a "regex error message" stating what the field should contain. My current mock up has that when the match count is zero, that would signify an error and to display the message. While still a white belt regex designer I have come to understand that in certain situations that it is difficult to write a regex which results in a match count of zero for every case. A complex regex case I looked for help on was Link Here. The forum post was a disaster because I confused people helping me. But one of the statements said that it was difficult to make a regex with a match count of zero meaning the input data was invalid; that the regex was very difficult to write that for. Does anyone have comments or suggestions on this generic validation system I am trying to create? thanks

    Read the article

  • IIS SEO Toolkit and W3C Validation Service

    - by The Official Microsoft IIS Site
    One thing that I’ve been asked several times about the SEO Toolkit is if it does a full standards validation on the markup and content that is processed, and if not, to add support for more comprehensive standards validation, in particular XHTML and HTML 4.01. Currently the markup validation performed by the SEO Toolkit is really simple, its main goal is to make sure that the markup is correctly organized, for example that things like <b><i>Test</b></i> are not found in the...(read more)

    Read the article

  • ISO 12207: Verification of integration and Unit test validation

    - by user970696
    I have received comments from the supervisor reviewing my thesis. He asked two questions I cannot answer right now: If ISO 12207 says under "Integration verification" that it "checks that components are correctly and completely integrated into a system", how this can be verified without testing, if all testing is validation? How without testing can I know that system is integrated correctly and fully? If unit testing is validation, how does it match the ISO definiton of validation "that requirements for intended use were fulfilled" if its so low level?

    Read the article

  • Best Method of function parameter validation

    - by Aglystas
    I've been dabbling with the idea of creating my own CMS for the experience and because it would be fun to run my website off my own code base. One of the decisions I keep coming back to is how best to validate incoming parameters for functions. This is mostly in reference to simple data types since object validation would be quite a bit more complex. At first I debated creating a naming convention that would contain information about what the parameters should be, (int, string, bool, etc) then I also figured I could create options to validate against. But then in every function I still need to run some sort of parameter validation that parses the parameter name to determine what the value can be then validate against it, granted this would be handled by passing the list of parameters to function but that still needs to happen and one of my goals is to remove the parameter validation from the function itself so that you can only have the actual function code that accomplishes the intended task without the additional code for validation. Is there any good way of handling this, or is it so low level that typically parameter validation is just done at the start of the function call anyway, so I should stick with doing that.

    Read the article

  • License validation and calling home

    - by VitalyB
    I am developing an application that, when bought, can be activated using a license. Currently I am doing offline validation which is a bit troubling to me. I am aware there is nothing to do against cracks (i.e modified binaries), however, I am thinking to trying to discourage license-key pirating. Here is my current plan: When the user activates the software and after offline validation is successful, it tries to call home and validate the license. If home approves of the license or if home is unreachable, or if the user is offline, the license gets approved. If home is reached and tells the license is invalid, validation fails. Licensed application calls home the same way every time during startup (in background). If license is revoked (i.e pirated license or generated via keygen), the license get deactivated. This should help with piracy of licenses - An invalid license will be disabled and a valid license that was pirated can be revoked (and its legal owner supplied with new license). Pirate-users will be forced to use cracked version which are usually version specific and harder to reach. While it generally sounds good to me, I have some concerns: Users tend to not like home-calling and online validation. Would that kind of validation bother you? Even though in case of offline/failure the application stays licensed? It is clear that the whole scheme can be thwarted by going offline/firewall/etc. I think that the bother to do one of these is great enough to discourage casual license sharing, but I am not sure. As it goes in general with licensing and DRM variations, I am not sure the time I spend on that kind of protection isn't better spent by improving my product. I'd appreciate your input and thoughts. Thanks!

    Read the article

  • Multiple Input Validation vulnerabilities in kerberos

    - by RitwikGhoshal
    CVE DescriptionCVSSv2 Base ScoreComponentProduct and Resolution CVE-2011-1528 Improper Input Validation vulnerability 7.8 Kerberos Solaris 11.1 11.1 CVE-2011-1529 Improper Input Validation vulnerability 7.8 CVE-2011-4151 Improper Input Validation vulnerability 7.8 This notification describes vulnerabilities fixed in third-party components that are included in Oracle's product distributions.Information about vulnerabilities affecting Oracle products can be found on Oracle Critical Patch Updates and Security Alerts page.

    Read the article

  • Django server side AJAX validation

    - by MMRUser
    Hi, Recently I'm trying to implement a simple Django application that include one server side AJAX validation, it's a simple form input field (username). I have used a pre-built in line AJAX validation library which uses jQuery. So the code goes like this HTML snippet <form id="simpleform" method="post" action="/done/"> Username:<input value="" class="validate[required,custom[noSpecialCaracters],length[0,20],ajax[ajaxUser]]" type="text" name="user" id="user" /> <input class="submit" type="submit" value="Validate"/> </form> The server side code snippet (embedded in to a php script) /* RECEIVE VALUE */ $validateValue=$_POST['validateValue']; $validateId=$_POST['validateId']; $validateError=$_POST['validateError']; /* RETURN VALUE */ $arrayToJs = array(); $arrayToJs[0] = $validateId; $arrayToJs[1] = $validateError; if($validateValue =="testname"){ // validate?? $arrayToJs[2] = "true"; // RETURN TRUE echo '{"jsonValidateReturn":'.json_encode($arrayToJs).'}'; // RETURN ARRAY WITH success }else{ for($x=0;$x<1000000;$x++){ if($x == 990000){ $arrayToJs[2] = "false"; echo '{"jsonValidateReturn":'.json_encode($arrayToJs).'}'; // RETURN ARRAY WITH ERROR } } } So my question is that how do I get this in to Python code (in order to use in Django environment) how do I get the user name from the input field in to the back end,I think the server side script snippet already does it but I want to know how to use this in my Pyhon code,and this is my first time using jQuery and I do need to use this same exact validation library. Your valuable corporation is needed. Thanks.

    Read the article

  • Getting started with XSD validation with C#

    - by Rosarch
    Here is my first attempt at validating XML with XSD. The XML file to be validated: <?xml version="1.0" encoding="utf-8" ?> <config xmlns="Schemas" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="config.xsd"> <levelVariant> <filePath>SampleVariant</filePath> </levelVariant> <levelVariant> <filePath>LegendaryMode</filePath> </levelVariant> <levelVariant> <filePath>AmazingMode</filePath> </levelVariant> </config> The XSD, located in "Schemas/config.xsd" relative to the XML file to be validated: <?xml version="1.0" encoding="utf-8" ?> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified"> <xs:element name="config"> <xs:complexType> <xs:sequence> <xs:element name="levelVariant"> <xs:complexType> <xs:sequence> <xs:element name="filePath" type="xs:anyURI"> </xs:element> </xs:sequence> </xs:complexType> </xs:element> </xs:sequence> </xs:complexType> </xs:element> </xs:schema> Right now, I just want to validate the XML file precisely as it appears currently. Once I understand this better, I'll expand more. Do I really need so many lines for something as simple as the XML file as it currently exists? The validation code in C#: public void SetURI(string uri) { XElement toValidate = XElement.Load(Path.Combine(PATH_TO_DATA_DIR, uri) + ".xml"); // begin confusion string schemaURI = toValidate.Attributes("xmlns").First().ToString() + toValidate.Attributes("xsi:noNamespaceSchemaLocation").First().ToString(); XmlSchemaSet schemas = new XmlSchemaSet(); schemas.Add("", XmlReader.Create( SOMETHING )); XDocument toValidateDoc = new XDocument(toValidate); toValidateDoc.Validate(schemas, null); // end confusion root = toValidate; } Any illumination would be appreciated.

    Read the article

  • Getting started with XSD validation with .NET

    - by Rosarch
    Here is my first attempt at validating XML with XSD. The XML file to be validated: <?xml version="1.0" encoding="utf-8" ?> <config xmlns="Schemas" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="config.xsd"> <levelVariant> <filePath>SampleVariant</filePath> </levelVariant> <levelVariant> <filePath>LegendaryMode</filePath> </levelVariant> <levelVariant> <filePath>AmazingMode</filePath> </levelVariant> </config> The XSD, located in "Schemas/config.xsd" relative to the XML file to be validated: <?xml version="1.0" encoding="utf-8" ?> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified"> <xs:element name="config"> <xs:complexType> <xs:sequence> <xs:element name="levelVariant"> <xs:complexType> <xs:sequence> <xs:element name="filePath" type="xs:anyURI"> </xs:element> </xs:sequence> </xs:complexType> </xs:element> </xs:sequence> </xs:complexType> </xs:element> </xs:schema> Right now, I just want to validate the XML file precisely as it appears currently. Once I understand this better, I'll expand more. Do I really need so many lines for something as simple as the XML file as it currently exists? The validation code in C#: public void SetURI(string uri) { XElement toValidate = XElement.Load(Path.Combine(PATH_TO_DATA_DIR, uri) + ".xml"); // begin confusion // exception here string schemaURI = toValidate.Attributes("xmlns").First().ToString() + toValidate.Attributes("xsi:noNamespaceSchemaLocation").First().ToString(); XmlSchemaSet schemas = new XmlSchemaSet(); schemas.Add(null, schemaURI); XDocument toValidateDoc = new XDocument(toValidate); toValidateDoc.Validate(schemas, null); // end confusion root = toValidate; } Running the above code gives this exception: The ':' character, hexadecimal value 0x3A, cannot be included in a name. Any illumination would be appreciated.

    Read the article

  • MVC validation error with strongly typed view

    - by Remnant
    I have a simple form that I would like to validate on form submission. Note I have stripped out the html for ease of viewing <%=Html.TextBox("LastName", "")%> //Lastname entry <%=Html.ValidationMessage("LastName")%> <%=Html.TextBox("FirstName", "")%>//Firstname entry <%=Html.ValidationMessage("FirstName")%> <%=Html.DropDownList("JobRole", Model.JobRoleList)%> //Dropdownlist of job roles <% foreach (var record in Model.Courses) // Checkboxes of different courses for user to select { %> <li><label><input type="checkbox" name="Courses" value="<%=record.CourseName%>" /><%= record.CourseName%></label></li> <% } %> On submission of this form I would like to check that both FirstName and LastName are populated (i.e. non-zero length). In my controller I have: public ActionResult Submit(string FirstName, string LastName) { if (FirstName.Trim().Length == 0) ModelState.AddModelError("FirstName", "You must enter a first name"); if (LastName.Trim().Length == 0) ModelState.AddModelError("LastName", "You must enter a first name"); if (ModelState.IsValid) { //Update database + redirect to action } return View(); //If ModelState not valid, return to View and show error messages } Unfortunately, this code logic produces an error that states that no objects are found for JobRole and Courses. If I remove the dropdownlist and checkboxes then all works fine. The issue appears to be that when I return the View the view is expecting objects for the dropwdownlist and checkboxes (which is sensible as that is what is in my View code) How can I overcome this problem? Things I have considered: In my controller I could create a JobRoleList object and Course object to pass to the View so that it has the objects to render. The issue with this is that it will overwrite any dropdownlist / checkbox selections that the user has already made. In the parameters of my controller method Submit I could aslo capture the JobRoleList object and Course object to pass back to the View. Again, not sure this would capture any items the user has already selected. I have done much googling and reading but I cannot find a good answer. When I look at examples in books or online (e.g. Nerddinner) all the validation examples involve simple forms with TextBox inputs and don't seems to show instances with multiple checkboxes and dropdownlists. Have I missed something obvious here? What would be best practice in this situation? Thanks

    Read the article

  • Simple Form validation failing Backbone

    - by Corey Buchillon
    Im not exactly adept at coding so Im probably missing something, but my view here is failing to refuse submission when one or both of the fields are empty. I have a feeling something isnt connected right to my template for the row and the view of the form Form = Backbone.View.extend({ //form vie el: '.item-form', initialize: function(){ }, events: { 'click #additem': 'addModel' }, addModel: function(itemName, price){ // simple validation before adding to collection if (itemName !="" && price !="" ){ var item = new Item({ itemName: this.$("#item").val(), price: this.$("#price").val()}); items.add(item); $("#message").html("Please wait; the task is being added."); item.save(null, {success: function (item, response,options) { item.id= item.attributes._id.$id; item.attributes.id = item.attributes._id.$id; new ItemsView({collection: items}); $("#message").html(""); } }); this.$("#item").val(''); this.$("#price").val(''); } else { alert('Please fill in both fields'); } } }); and HTML <table class="itemTable"> <thead> <tr> <th>Item</th> <th>Price</th> <th></th> </tr> </thead> <tbody class="tableBody"> <script type="text/template" id="table-row"> <td><%= itemName %></td> <td><%= price %></td> <td><button class="complete">Complete</button> <button class="remove">Remove</button></td> </script> </tbody> </table> <form class="item-form"> <input type="text" name="item" id="item" placeholder="Item"/> <!-- goes to itemName in the template for the body --> <input type="text" name="price" id="price" placeholder="Price" /><!--goes to price in the template for the body --> <button type="button" id="additem">Add</button> </form> <div id="message"></div>

    Read the article

  • Comparing char for validation in C++

    - by Corey Starbird
    /* PROGRAM: Ch6_14.cpp Written by Corey Starbird This program calculates the balance owed to a hospital for a patient. Last modified: 10/28/13 */ #include <iostream> #include <fstream> #include <iomanip> #include <string> using namespace std; // Prototypes for In-patient and Out-patient functions. double stayTotal (int, double, double, double); // For In-patients double stayTotal (double, double); // For Out-patients int main() { char patientType; // In-patient (I or i) or Out-patient (O or o) double rate, // Daily rate for the In-patient stay servCharge, // Service charge for the stay medCharge, // Medication charge for the stay inTotal, // Total for the In-patient stay outTotal; // Total for the Out-patient stay int days; // Number of days for the In-patient stay // Find out if they were an In-patient or an Out-patient cout << "Welcome, please enter (I) for an In-patient or (O) for an Out-patient:" << endl; cin >> patientType; while (patientType != 'I' || 'i' || 'O' || 'o') { cout << "Invalid entry. Please enter either (I) for an In-patient or (O) for an Out-patient:" << endl; cin >> patientType; } cout << "FIN"; return 0; } Hey, brand new to C++ here. I am working on a project and I'm having trouble figuring out why my validation for patientTypeisn't working properly. I first had double quotes, but realized that would denote strings. I changed them to single quotes, my program will compile and run now, but the while loop runs no matter what I enter, I, i, O, o, or anything else. I don't know why the while loop isn't checking the condition, seeing that I did enter one of the characters in the condition, and move on to cout. Probably a simple mistake, but I thank you in advance.

    Read the article

  • jstree dynamic JSON data from django

    - by danspants
    I'm trying to set up jsTree to dynamically accept JSON data from django. This is the test data i have django returning to jstree: result=[{ "data" : "A node", "children" : [ { "data" : "Only child", "state" : "closed" } ], "state" : "open" },"Ajax node"] response=HttpResponse(content=result,mimetype="application/json") this is the jstree code I'm using: jQuery("#demo1").jstree({ "json_data" : { "ajax" : { "url" : "/dirlist", "data" : function (n) { return { id : n.attr ? n.attr("id") : 0 }; }, error: function(e){alert(e);} } }, "plugins" : [ "themes","json_data"] }); All I get is the ajax loading symbol, the ajax error response is also triggered and it alerts "undefined". I've also tried simpleJson encoding in django but with the same result. If I change the url so that it is receiving a JSON file with identical data, it works as expected. Any ideas on what the issue might be?

    Read the article

  • django ignoring admin.py

    - by noam
    I am trying to enable the admin for my app. I managed to get the admin running, but I can't seem to make my models appear on the admin page. I tried following the tutorial (here) which says: (Quote) Just one thing to do: We need to tell the admin that Poll objects have an admin interface. To do this, create a file called admin.py in your polls directory, and edit it to look like this: from polls.models import Poll from django.contrib import admin admin.site.register(Poll) (end quote) I added an admin.py file as instructed, and also added the following lines into urls.py: from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', ... (r'^admin/', include(admin.site.urls)), ) but it appears to have no effect. I even added a print 1 at the first line of admin.py and I see that the printout never happens, So I guess django doesn't know about my admin.py. As said, I can enter the admin site, I just don't see anything other than "groups", "users" and "sites". What step am I missing?

    Read the article

< Previous Page | 62 63 64 65 66 67 68 69 70 71 72 73  | Next Page >