locked
Disable "Required" validation on Not Null fields RRS feed

  • Question

  • User-986098262 posted
    Hey People! What's the right way to disable "Required" validation on Not Null fields of scaffolded table? Changing the table definition in the database is not an option. Thanks
    Tuesday, December 16, 2008 12:32 PM

Answers

  • User660823006 posted

    If you want to prevent Dynamic Data from requiring the fields you can do this by disabling the RequiredFieldValidator in the field templates. If you look in  \DynamicData\FieldTemplates in your project you will see a variety of things like Text_Edit.ascx. The _Edit versions are the ones used for editing the data in Dynamic Data. You can simply go in there and comment out the RequiredFieldValidator and the call in the code behind that will look like SetupRequiredValidator. This will prevent Dynamic Data from trying to make any field required. If you wanted to do this selectively you could create your own attribute to place on the model and when you detect it in the field template disable the validation.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, December 16, 2008 1:07 PM
  • User-797310475 posted

    I see you already noticed that problem. Actually, here's a slightly better solution, since you basically want to disable the validator only in insert mode. In edit mode the default value is no longer going to be used: 

    if (noReqValidation && this.Mode == DataBoundControlMode.Insert) {
        IgnoreModelValidationAttribute(typeof(RequiredAttribute));
    } else {
        SetUpValidator(RequiredFieldValidator1);
    }
    SetUpValidator(DynamicValidator1);
     
    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, December 16, 2008 4:51 PM
  • User-330204900 posted

    I don't know if you know but you will need to ExecuteDynamicInsert(instance); once you have finished your validation to commit your insert.

    Hope this helps [:D]

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, December 17, 2008 10:57 AM

All replies

  • User-1005219520 posted

    repeating from previous thread

    It would be a mistake to change the schema to allow nulls - you don't want to do that. For some fields you want the DB to supply the value (via defaults from the DB). What you really want is allow NULL at the client (ASP.Net side) but not allow nulls on the server (the server will supply the value).

    The easiest way to do this is with scaffoldColumn(false) to hide those columns. The problem with that approach is you never see the hidden fields - even on List and details pages where you are just reading them. You can use Steve's approach to hide the fields on insert. Look for hiding columns at http://csharpbits.notaclue.net 

    Once you hide the field on insert - there will be no validation for the field.

    Tuesday, December 16, 2008 12:40 PM
  • User-986098262 posted
    I don't want to hide the fields, but rather allow the user to submit the insert form with empty fields. By default I get "Required" validation errors on all empty fields.
    Tuesday, December 16, 2008 12:58 PM
  • User660823006 posted

    If you want to prevent Dynamic Data from requiring the fields you can do this by disabling the RequiredFieldValidator in the field templates. If you look in  \DynamicData\FieldTemplates in your project you will see a variety of things like Text_Edit.ascx. The _Edit versions are the ones used for editing the data in Dynamic Data. You can simply go in there and comment out the RequiredFieldValidator and the call in the code behind that will look like SetupRequiredValidator. This will prevent Dynamic Data from trying to make any field required. If you wanted to do this selectively you could create your own attribute to place on the model and when you detect it in the field template disable the validation.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, December 16, 2008 1:07 PM
  • User-986098262 posted

    Hey! Great solution.

     That's what I did:

     

    [AttributeUsage(AttributeTargets.Property| AttributeTargets.Field, AllowMultiple=false)]
    public class NotRequiredAttribute : System.Attribute
    {
        public override object TypeId { get { return this; } }
        public NotRequiredAttribute(bool value)
        {
            this._value = value;
        }
    
        private bool _value;
        public bool Value
        {
            get { return this._value; }
        }
    }
    

     

    And this in the template code behind:

      

            var noReqValidAttribute = Column.Attributes[typeof(NotRequiredAttribute)] as NotRequiredAttribute;
            bool noReqValidation = noReqValidAttribute == null ? false : noReqValidAttribute.Value;
    
            if(!noReqValidation)        
                SetUpValidator(RequiredFieldValidator1);

     

    It works.

     But is there a more elegant solution? Maybe there is a way I can remove the "Required" attribute from the selected fields?

    I think it's added by default by dynamic data because the fields are Not Null.

     

    Thanks

    Tuesday, December 16, 2008 2:12 PM
  • User-797310475 posted

    Hi Michael,

    The insertion of RequiredAttribute is something that Dynamic Data does automatically for columns which are marked as NOT NULL in the database. There currently is no way to disable this behavior, other than writing your own implementation of a Model Provider. Could you explain your requirement in more detail. If the field in the database is not nullable, then why would you want to allow users to leave those fields empty?

    Tuesday, December 16, 2008 2:19 PM
  • User-986098262 posted

    Well, I want to leave the user an option to leave the field empty. An empty field submited, in the database would become an empty string for varchar fields or 0 for int fields...

     

    Tuesday, December 16, 2008 2:24 PM
  • User-797310475 posted

    Just read your other post and now I see. Sorry for the confusion caused by the people who were trying to answer but clearly don't know what Dynamic Data is.

    Are you using LINQ to SQL or Entity Framework? If it is LINQ to SQL then in the model designer you can tweak your selected columns and mark them as Auto Generated Value = true in the Properties view and Dynamic Data should pick up on it (you might need to annotate those columns with ScaffoldColumn(true) however, as they will be omitted from the automatic scaffolding).

    In Entity Framework there is nothing you can do, unfortunately. You will have to use the workaround with the new attribute.

    Tuesday, December 16, 2008 2:33 PM
  • User-986098262 posted

    Hey!

    I am using LINQ to SQL. Marked the fields as Auto Generated Value and annotated with ScaffoldColumn(true), they get scaffolded but in the insert page there is no input element for those fields, just their name and an empty space.

     Thanks

    Michael

     

    Tuesday, December 16, 2008 3:17 PM
  • User-1005219520 posted

    What is the SQL type?

    Tuesday, December 16, 2008 3:26 PM
  • User-986098262 posted

    NVarChar(50) NOT NULL

    Tuesday, December 16, 2008 3:33 PM
  • User-986098262 posted

    I am having trouble disabling the RequiredFieldValidator control in the field template.

    Not calling SetUpValidator(RequiredFieldValidator1); and setting RequiredFieldValidator1.Enabled = false;

    removes the validation only from client side but not from server side, so I get the same error messages but this time

    via AJAX.

    What is the right way to disable the RequiredFieldValidator1 control in the field templates? (I am using the custom attribute solution)

     

    Thanks

    Michael

    Tuesday, December 16, 2008 4:33 PM
  • User-797310475 posted

    And this in the template code behind:

      

            var noReqValidAttribute = Column.Attributes[typeof(NotRequiredAttribute)] as NotRequiredAttribute;
            bool noReqValidation = noReqValidAttribute == null ? false : noReqValidAttribute.Value;
    
            if(!noReqValidation)        
                SetUpValidator(RequiredFieldValidator1);

     

    It works.

     

    You said the solution using a new attribute works, but I'm surprised that it does because of the RequiredAttribute that gets automatically injected, which will get used by the instance of DynamicValidator that is present in your field template. The solution is to add the RequiredAttribute to a list of exclusion types. Basically, you will want to modify your code from earlier with this: 

    <STRIKE>if (!noReqValidation) {
        SetUpValidator(RequiredFieldValidator1);
    } else {
        IgnoreModelValidationAttribute(typeof(RequiredAttribute));
    }
    SetUpValidator(DynamicValidator1);</STRIKE>
    The IgnoreModelValidationAttribute method will set a flag for DynamicValidator to ignore attributes of that type
    Tuesday, December 16, 2008 4:46 PM
  • User-797310475 posted

    I see you already noticed that problem. Actually, here's a slightly better solution, since you basically want to disable the validator only in insert mode. In edit mode the default value is no longer going to be used: 

    if (noReqValidation && this.Mode == DataBoundControlMode.Insert) {
        IgnoreModelValidationAttribute(typeof(RequiredAttribute));
    } else {
        SetUpValidator(RequiredFieldValidator1);
    }
    SetUpValidator(DynamicValidator1);
     
    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, December 16, 2008 4:51 PM
  • User-986098262 posted

    Hey!

     

    Thanks. It's working.

    I have extended the data context Insert method and check there for null values, converting them to String.Empty's. Only problem now is that the new record doesn't show in the database... I'll try to debug it now..

     

    Michael

    Wednesday, December 17, 2008 8:07 AM
  • User-330204900 posted

    I don't know if you know but you will need to ExecuteDynamicInsert(instance); once you have finished your validation to commit your insert.

    Hope this helps [:D]

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, December 17, 2008 10:57 AM
  • User-712392223 posted

    Hey folks,

    I had been working with the code indicated here to try to solve my own problem of allowing empty strings to be submitted for a not null field and for whatever reason, the code here didn't seem to work for me.

    I ended up answering my own question by coming up with a different approach. In case anyone else comes here looking to do what I wanted and is looking for alternatives, I posted the answer here: http://forums.asp.net/p/1400883/3031242.aspx#3031242. It is actually amazingly simple.

    Later,

    Chris

    Monday, March 23, 2009 4:22 PM
  • User-1169605399 posted


    I have noticed similar odd behavior in Dynamic Data regarding non-required, nullable text fields.

    I have a DB field MiddleName which is nullable and not required. In my DBML Mapping, it comes over as

    [global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_MiddleName", DbType="NVarChar(200)")]

    or, Ive tried forcing nullability (to no effect):
    [global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_MiddleName", DbType = "NVarChar(200)", CanBeNull = true)]

    Since it is a text field, it gets mapped automatically to Text_Edit.ascx field control while in Edit mode.

    MSDN states : If the field in the database cannot be null, or if a Required attribute is added to the data model, Text_Edit.ascx also renders a RequiredFieldValidator control.

    However, in my case, without a required attribute, unnecessary validation code is generated regardless. Inspecting my source code I get generated javescript for MiddleName validation
    <script type="text/javascript">
    //<![CDATA[
    var Page_ValidationSummaries = new Array(document.getElementById("MainContent_ContentPlaceHolder1_ValidationSummary1"));
    var Page_Validators = new Array(document.getElementById("MainContent_ContentPlaceHolder1_DetailsViewValidator"), document.getElementById("MainContent_ContentPlaceHolder1_FormView1_ctl02___MiddleName_RequiredFieldValidator1"), document.getElementById("MainContent_ContentPlaceHolder1_FormView1_ctl02___MiddleName_RegularExpressionValidator1"), document.getElementById("MainContent_ContentPlaceHolder1_FormView1_ctl02___MiddleName_DynamicValidator1"),
    //etc.
    //]]>
    </script>

    I realize I can make a new version of a text_Edit control without validation, but it seems like this behavior contradicts what MSDN says. Has anyone else found a better (easier) solution?

    Tuesday, October 9, 2012 4:40 PM
  • User-330204900 posted

    Hi Matt, when you debug the Text_Edit field template and look at the column is it set to required? also check the line of code

    SetUpValidator(RequiredFieldValidator1);

     in the Page_Load event and see if this is setting up the validator.

    Wednesday, October 10, 2012 7:30 AM