Link to home
Start Free TrialLog in
Avatar of Crystal Rouse
Crystal RouseFlag for United States of America

asked on

Validating a Form in MVC

I'm trying to add JavaScript validation to checkboxes and a text box in MVC.  Just can't figure out what I'm missing.  It's MVC and I'm new to this way of doing things.

My View has  form with checkboxes:

 <div class="row">
                        <div class="col-xs-1">
                            @Html.CheckBoxFor(x => x.test1, new
                                { @class = "form-control",
                                  @id = "test1"
                                })           
                        </div>

                        <div class="col-xs-4" style="margin-left:-20px;">
                            <div style="font-weight:600;">
                                Test 1
                                </div>
                            </div>

                        <div class="col-xs-1">
                            @Html.CheckBoxFor(x => x.Test2, new
                       {
                           @class = "form-control",
                           @id = "Test2"
                       })                      
                        </div>
                        
                        <div class="col-xs-4" style="margin-left:-20px;">
                            <div style="font-weight:600;">Test 2</div>
                        </div>
                    </div>

Open in new window


I also have this at the top of my view:

<script type="text/javascript">
    var NewRequest = new NewRequestClass();
    NewRequest.init();
</script>

Open in new window


On my submit button I have this onclick:  onclick="NewRequest.validateForm(this.form)";

The javascript file lools like:

function NewRequestClass() {
    this.Test1;
    this.Test2;
   
}

NewRequestClass.prototype = {

//Maps variables to the correct field
    init: function () {
        this.test1 = document.getElementById("Test1");
        this.test2 = document.getElementById("Test2");

    },

validateForm: function (sender) {

        if ((this.test1.checked == false) && (this.test2.checked == false)
        
        ) {
            swal({
                title: "Required Fields",
                text: "You must check at least one Request",
                type: "warning",
                showCancelButton: true,
                closeOnCancel: true
            });
        }

    },

}

Open in new window


I'm getting an error that test1 is undefined.  What am I missing?
Avatar of Dustin Saunders
Dustin Saunders
Flag of United States of America image

For forms where I have a required answer, I use 'required'.  If you're doing some custom validation or validation on some sort of dynamic generated form this is a good approach.

querySelectorAll is your friend (you can do from elements but in this example I'll use document)
<html>
<head>

</head>
<body>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<div class="row">
                        <div class="col">
							<input type="checkbox" class="form-control" id="test1" required>
							</input>      
                        </div>

                        <div class="col">
                            <div style="font-weight:600;">
                                Test 1
							</div>
						</div>

                        <div class="col">
                            <input type="checkbox" class="form-control" id="test2" required>
							</input>            
                        </div>
                        
                        <div class="col">
                            <div style="font-weight:600;">Test 2</div>
                        </div>
						
						<div class="col">
                            <input type="checkbox" class="form-control" id="test3">
							</input>            
                        </div>
                        
                        <div class="col">
                            <div style="font-weight:600;">Test 3</div>
                        </div>
</div>
					<button onclick="validate()">Validate</button>


<script>
function validate(){
	var requiredElements = document.querySelectorAll('[required]');
	var notComplete = 0;
	for(i = 0; i<requiredElements.length; i++) {
		if(!requiredElements[i].checked)
		{
			notComplete++;
		}
	}
	alert(notComplete);
}
</script>
</body>

</html>

Open in new window


This will check for checked boxes and then alert how many aren't checked.  You could do different validation based on different criteria based on different attribute tags for the boxes.  Since you're iterating each one, you can consider different "validations" depending on type or tag.

Notice here there are 3 elements, 2 of which are required.

i.e.
Let's say I tag a "text" input with the attribute 'data-serialNumberType', on validation if required I can use that and say "the pattern needs to be XXX-XX-XXX".  Since you're using each one individually, inside that validation you can also tack on the errors or change the class to "danger" to show that its required.
Avatar of Crystal Rouse

ASKER

Thanks!  I actually have a set of checkboxes that I need to require that at least one is checked or the user enters text in a text field.
I thought about using Required but didn't think it would work for my situation.
ASKER CERTIFIED SOLUTION
Avatar of Dustin Saunders
Dustin Saunders
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
I'm getting an error that test1 is undefined

You get this error since the compilator can't find the related appropriate elements, The main problem comes from those two lines :

this.test1 = document.getElementById("Test1");
this.test2 = document.getElementById("Test2");

Open in new window


Javascript is case sensitive, you've id's in lowercase and you're trying to get them capitalized, it should be :

this.test1 = document.getElementById("test1");
this.test2 = document.getElementById("test2");

Open in new window


For the rest of your code, it looks just fine.
I really like the example of adding an attribute!  I am getting an error of:  Invalid anonymous type member declarator.  Is there somewhere I'm supposed to declare the new attribute?

I'm adding this to my checkboxes:

@data-requirementgroup = "1"
Try it without the @ symbol:

<div class="col-xs-1">
                            @Html.CheckBoxFor(x => x.test1, new
                                { @class = "form-control",
                                  @id = "test1",
                                  data_requirementgroup = "1"
                                })           
                        </div>

Open in new window

That worked and also changing it to data_requirementgroup with an underscore.
I get a value of false whatever I try.  Even if I check a few and enter text.  So, I need to either have one of the checkboxes checked or text entered in the text field.  Any ideas? And Thanks so much for your help!  JavaScript is just not my cup of tea and especially getting it to work with MVC Views.
If you open the browser console, do you get any errors when you run it?  Works appropriately on my test here, do you have jquery added as a source?

https://jsfiddle.net/dustinsaunders/cqgsn5hj/13/
A co-worked helped me out.   For some reason, the browser rendered data_requirementgroup as data-requirementgroup in the DOM.
Ah, yes the _ will be converted to a - in the markup.

Iirc you could also do

@Html.CheckBoxFor(x => x.test1, new
                                { @class = "form-control",
                                  @id = "test1",
                                  new Dictionary<string,object> {"data-requirementgroup","1"}
                                })  

Open in new window

Thanks  so much for all of the help from everyone!  This has been a journey and I really appreciate the suggestions and code examples.
Happy to help!