I have a form which has a select
element, if the option 'Other' is selected a textarea
will dropdown asking for extra information.
I want this textarea
to be required unless the select
option isn't 'Other'.
How would I go about doing this?
JavaScript (submitting the form to a controller)
var submitAnimatedForm = function (formHold, controllerURL, successMessage) {
if (formHold.length) {
var _form = formHold.find("form");
_form.on("submit", function (e) {
e.preventDefault();
// Disables submit button on click
$(':input[type=submit]').prop('disabled', true);
// If the form is valid, post AJAX.
if (_form.valid()) {
setTimeout(function () {
$.ajax({
type: 'POST',
url: '/Umbraco/Surface/Contact/SubmitQuote',
data: _form.serialize(),
dataType: 'json',
encode: true,
success: function (data) {
if (!data.success) {
alert("ERR"); // - This is what I keep getting back
} else {
alert("SUCCESS");
}
},
error: function (data) {
console.log("ERR");
}
});
}, 2000);
}
});
}
};
C# (Checking the model data)
Controller:
if (!ModelState.IsValid)
{
return Json (
new
{
success = false,
message = "Sorry, we encountered an error."
}
);
}
return Json (
new
{
success = true,
message = "Thank you, your request has been sent!"
}
);
Model
public class ServiceModel
{
[Required(ErrorMessage = "Your first name is required")]
public String Firstname { get; set; }
[Required(ErrorMessage = "Your last name is required")]
public String Lastname { get; set; }
[Required(ErrorMessage = "Your e-mail address is required")]
[DataType(DataType.EmailAddress)]
public String Email { get; set; }
[Required(ErrorMessage = "Your job location is required")]
public String Location { get; set; }
[Required(ErrorMessage = "This field is required")]
public String Service { get; set; }
[Required(ErrorMessage = "Your job description is required")]
public String Description { get; set; }
public String EstimatedCost { get; set; }
}
I assume it's something to do with my C# code, I believe I could do a fix like so:
if (objModel.Service == "Other")
{
if (String.IsNullOrWhitespace(objModel.Description))
{
return Json (
new
{
success = false,
message = "Please fill out your description!"
}
)
}
}
else
{
// - Send an e-mail
}
But the issue with this is the fact that it's not checking the rest of the model and only the service description.
Any help would be appreciated! :)
Thanks