loyalflow
loyalflow

Reputation: 14929

Adding validation to dynamic forms

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"  />

Upvotes: 2

Views: 5176

Answers (10)

Willian Andrade
Willian Andrade

Reputation: 332

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.

Upvotes: 0

Ahsan Mahboob Shah
Ahsan Mahboob Shah

Reputation: 4029

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()) {
    ...

Upvotes: 0

Sunil Verma
Sunil Verma

Reputation: 2500

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, comment for more info or a small demo form.

Upvotes: 0

Parag Kuhikar
Parag Kuhikar

Reputation: 485

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.

Upvotes: 0

Alessio Koci
Alessio Koci

Reputation: 1113

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

Upvotes: 1

mayabelle
mayabelle

Reputation: 10014

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

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.

Upvotes: 0

Parris
Parris

Reputation: 18456

If you can output a json blob of validations you can use this: https://github.com/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.

Upvotes: 0

Parv Sharma
Parv Sharma

Reputation: 12705

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 coming 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>
}

Upvotes: 4

reggaemahn
reggaemahn

Reputation: 6668

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.org/documentation/

Upvotes: 2

Mgetz
Mgetz

Reputation: 5138

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.

Upvotes: 0

Related Questions