最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Adding validation to dynamic forms - Stack Overflow

programmeradmin1浏览0评论

I pull what to display on a particular form from my database, so the form elements are dynamic.

I display radio buttons, or checkboxes or textboxes/textareas depending on how I want the form to display.

Before someone submits the form, I have to validate that each form entry (radio, checkbox, textbox etc) has been selected.

How can I insert validation to these dynamic form elements?

Example:

<input type="checkbox" id="@formInputId" name="@formInputName" value="@element.Id"  />

I pull what to display on a particular form from my database, so the form elements are dynamic.

I display radio buttons, or checkboxes or textboxes/textareas depending on how I want the form to display.

Before someone submits the form, I have to validate that each form entry (radio, checkbox, textbox etc) has been selected.

How can I insert validation to these dynamic form elements?

Example:

<input type="checkbox" id="@formInputId" name="@formInputName" value="@element.Id"  />
Share Improve this question edited Sep 13, 2013 at 19:26 loyalflow asked Sep 13, 2013 at 19:02 loyalflowloyalflow 14.9k31 gold badges111 silver badges175 bronze badges 8
  • 1 How is it dynamic? your view is based on a model with specific properties, isn't it? – Abbas Amiri Commented Sep 13, 2013 at 19:38
  • you mean jquery validation?only on client side? – Milad Hosseinpanahi Commented Sep 13, 2013 at 19:46
  • @AbbasAmiri Yes I have a strongly typed viewmodel, like I loop through them like @foreach (FormElement element in Model.FormElements) but the # of elements es from the database. Yes validation on the client side is what I am looking for. – loyalflow Commented Sep 13, 2013 at 19:55
  • @user1361315 I remend to you using HtmlHelpers, they make your view clean and easy to maintain and I can't see any problem of using them with your scenario. Validation is pletely supported by HtmlHelpers. – Abbas Amiri Commented Sep 13, 2013 at 20:04
  • I'll look into that, but for now it isn't using htmlhelpers, how can I do it manually? – loyalflow Commented Sep 18, 2013 at 13:46
 |  Show 3 more ments

10 Answers 10

Reset to default 4 +50

to get started, you can also inject JSON/Javascript into the view. Though this is not preffered because then you wont be able to make a separate js file out of it. But in case of validation of dynamic forms i did this earlier.

since your form ids are ing from the database you know Id of each control therefore you can identify each element separately using jquery.

jquery validation plugins makes it very easy to add validation rules. So you just make the validation rules server side with something like this.

forEach(FormElement element in Model.FormElements){
 dynamic rules = new ExpandoObject();
 //set all the rule here.
 ViewBag.ElementId = rules;
}

basic rules structure is given here.

Then inside the view when you are rendering the controls. check for

@if(ViewData.ContainsKey("[ElementId]")){
//if it exists
//inject json using newtonsoft json
<script>
$('#@Html.raw([ElementId])').rules("Add", JsonConvert.SerializeObject(ViewData["ElementId"]))
</script>
}

Have you looked at the jquery validation plugin? Why try to reinvent the wheel. It's pretty simple to use.

Check this Demo

Here is the link to the official docs. http://jqueryvalidation/documentation/

Html

<form id="myform">
<input name="product[0][name]" id="form_product[0][name]" data-rule-required="true" />
<input name="product[1][name]" id="form_product[1][name]" data-rule-required="true" />
<input name="product[2][name]" id="form_product[2][name]" data-rule-required="true" />
<br/>
<br/>
<br/>
<input type="submit" />



add one field Validation Documentation

css

#docs {
display: block;
position: fixed;
bottom: 0;
right: 0;

}

js

$(document).ready(function () {

$('#myform').validate({ // initialize the plugin      
    submitHandler: function (form) { // for demo
        alert('valid form submitted'); // for demo
        return false; // for demo
    }
});

$('button').one('click', function () {
    $('#myform').append('<input name="product[3][name]" id="form_product[3][name]" data-rule-required="true">');
});});

DEMO jsfiddle HERE

You should be able to parse the elements dynamically with the unobtrusive validation, however you'll need to add the appropriate attributes to trigger the appropriate validation first. Fundamentally it's very similar to what's happening in this question where they are adding elements dynamically by javascript.

If you can output a json blob of validations you can use this: https://github./parris/iz#json

It will let you specify a JSON blob of rules as such:

var rules = {
    'cost': [
        {
            'rule': 'between',
            'args': [17, 1000],
            'error': 'The cost must be between 17, 1000'
        },
        {
            'rule': 'required',
            'error': 'You must specify a cost'
        },
    ],
    'producer.id': [
        {
            'rule': 'int',
            'error': 'Producer ID must be an int'
        }
    ],
    'producer.name.first': [
        {
            'rule': 'alphaNumeric',
            'error': 'Must be names and numbers'
        }
    ]
};

Then collect your values and validate like this:

are(rules).validFor({
    cost: 20,
    producer: {
        id: 1,
        name: {
            first: 'bob'
        }
    }
});

It has some built in validations that should pretty closely match what you need. If not, you can shim in some custom validations.

Note: Iz, is a library I wrote, and yes I am totally pitching it to you right now.

The JQuery Validate plugin should work (see http://jqueryvalidation).

It sounds like all you need is to mark all fields required, so you can add a required rule to them by using a class, which would avoid having to coordinate ids/names of your dynamic elements between the model and the javascript.

Change your input line to:

<input type="checkbox" id="@formInputId" name="@formInputName" 
    value="@element.Id" class="requiredField" />

Then in your javascript:

$(document).ready(function() {
    var form = $( "#MyForm" );
    form.validate();

    jQuery.validator.addClassRules('requiredField', {
        required: true
    });

    form.on('submit', function () {
        if (form.valid()) {
            form.submit();
        }
    });
});

You can also check validity of individual elements by using (selector).valid(). You can add other validation rules (besides required) by adding to the list of class rules.

You could also use Jquery Validate engine .

In which, you just have to manage class attribute of the dynamic element.

I suggest you, you could use Hook of Jquery Validate Engine.

It will be easy for you.

I have recently answered a question where we do no of things with jQuery, if you want to user custom jQuery, take reference as follows:

On form element you can use recursive code for ex: in case of a checkbox

$(document).ready(function () {
    $('#new_user_form *').filter(':checkbox').each(function(){
        if(this.id=='row1' && this.value=='3') {
        } else {
            $(this).attr("checked",false);
        }
    });
});

Will work same for other type of element i.e input, radio etc.

On selecting a checkbox disable spefic checkboxes

Review above for more, ment for more info or a small demo form.

i have achieved the same requirement using jQuery Validation Plugin

Place the following code in script section of your page. you need to add the form-data class to your form and add required_field while adding the elements to page.

var validator = null;
$(document).ready(function () {
    try {
        var validatedForm = $(".form-data");
        validator = validatedForm.validate && validatedForm.validate({
            rules: {
                required_field: {
                    required: true
                }
            },
            messages: {
                required_field: {
                    required: " "
                }
            },
            errorElement: "span",
            showErrors: function (errorMap, errorList) {
                this.defaultShowErrors();
            },
            highlight: function (element) {
                // do something like
                $(element).closest('...').removeClass('success').addClass('error');
            },
            unhighlight: function (element) {
                // do something like
                $(element).closest('...').removeClass('error');
            },
            submitHandler: function(form) {
                // submit form
                form.submit();
            }
            success: function (element) {
                // do something like
                $(element).closest('...').removeClass('error').end().remove();
            },
            onfocusout: function (element) {
                $(element).valid();
            },
        });

        $.each($(".required_field"), function (index, value){
            $(value).rules( "add", {
                  required: true,
                  messages: {
                      required: " "
                  }
            });
        });
    } catch(err) {
        console.log("javascript error", err);
    }
});

While submitting you can check if the form is valid or not:

if($('#formId').valid()) {
    ...

i guess the best way is make your client-side validation using $.validate plugin and in your POST action create methods to validate your data. I always suggest to not mix javascript with csharp, or others places, to maintains things organized.

发布评论

评论列表(0)

  1. 暂无评论