0

I am using .NET core with boilerplate framework and am having trouble with client-side data validation. From what I understand, the data annotations used in the DTO's are validated server-side. I am looking for a way to do this validation client-side, and I thought I could just use it by creating an object of that DTO in my view models and using the view model validation the way I am used to doing it with .NET core.

What I Am Trying to Do:

I am trying to get data validation in my form using Data annotations from the DTO. My view model contains a DTO object as a property and uses that in it's form. It seems it does the validation as it will not submit until everything is correct, however, it will not show any validation EXCEPT for validation for the email input; and I am not sure why it will do it for email and nothing else.

Here is my View

<form asp-action="AddEmergencyContactPost" method="post" id="addEmergencyContactForm" role="form">
<div class="row clearfix">
  <div class="col-sm-12">
    <div class="form-group form-float">
      <div class="form-line">
        <input asp-for="EmergencyContact.PhoneNumber" type="tel" class="validate form-control">
        <label asp-for="EmergencyContact.PhoneNumber" class="form-label"></label>
        <span asp-validation-for="EmergencyContact.PhoneNumber" class="text-danger"></span>
      </div>
    </div>
  </div>
</div>
</form>

Here is my DTO property and how the view model is using the object

//DTO property
[Required]
[StringLength(10, MinimumLength = 10, ErrorMessage = "Invalid Phone Number")]
public string PhoneNumber { get; set; }

//View Model
public CreateEmergencyContactDto EmergencyContact { get; set; }

And here is the javascript that is handling the request

$("#addEmergencyContactForm").on("submit",
        function (e) {
            e.preventDefault();
            debugger;
            $.ajax({
                url: this.action,
                type: this.method,
                data: $(this).serialize(),
                success: function (data) {
                    if (data.result === "success") {
                        swal({
                            title: "Emergency Contact Added",
                            icon: "success"
                        }).then(function () {
                            location.reload();
                        });

                    } else {
                        swal({
                            title: "Please Enter the Correct Type of Data",
                            icon: "warning"
                        }).then(function () {
                            location.reload();
                        });
                    }
                    _$modal.modal("toggle");
                }
            });
        });

What I've Tried So Far:

So far i've tried adding a type to the tag helper of 'tel' and returning the view if the Model State is not valid. I have also tried making the object in the View Model required, but that only sets required tags for all the fields (and for some reason only does that validation for one field at a time). Below is a gif showing how the email validates but nothing does. enter image description here

I've also tried using jquery validate, but whenever I test if the form is valid it always returns true no matter what. I also tried setting the validation flags explicitly, but then I get an error shown below enter image description here

Here is the code I used to add the explicit validation.

$(this).validate({
                rules: {
                    EmergencyContact.PhoneNumber: {
                        required: true,
                        minlength: 10,
                        phoneUS: true
                    }
                },
                messages: {
                    EmergencyContact.PhoneNumber{
                    required: "Please Enter A Phone Number",
                    phoneUS: "Please Enter A Valid Phone Number",
                    minLength: "Please Enter A Valid Phone Number"

                }
            }
        });

So, is there a way to do this client side validation with these data annotation helpers? And if not what would be the easiest way to do this client-side validation for my form which is contained in my index and not in a partial? Thanks ahead of time for any help you can give.

EDIT: Here is the startup template i'm using from boilerplate

enter image description here

3
  • 1
    Your images shows you are not implementing mvc client side validation (using jquery.validate.unobtrusive.js and query.validate.js) - that is just HTML5 validation. You need to include the relevant scripts in your view or layout
    – user3559349
    Oct 15, 2018 at 22:44
  • 1
    And as a side note, view models do not contain data models when editing. They contain the properties of your data models that you need in the view. What is ViewModel in MVC?
    – user3559349
    Oct 15, 2018 at 22:45
  • 1
    And if you are submitting via ajax, you also need to check if the form is valid and if not cancel the ajax i.e. - if (!$(this).valid()) { return; }
    – user3559349
    Oct 15, 2018 at 22:48

1 Answer 1

0

My understanding of the view-model validation was a bit off. I was thinking it would provide client-side validation, but instead it provided server-side validation. The validation seen showing up occurred from browser validation.


For client-side validation I ended up using parsley which validated my data through tag-helpers.


For server-side validation I used some Boilerplate features to throw the error as Json and then display the error using Toastr. An example of this follows. This would be my controller method I'm calling to save a form

if ()
{
    throw new UserFriendlyError("Message");
}

And then I would deal with the error in the ajax call

error: function(jqXHR){
    abp.notify.error(jqXHR.responseJSON.error.message);
}

I'm sure there are better ways to do these things, but so far this is what I found works best for me.


EDIT:

As @aaron pointed out if I were to use abp.ajax the error would be displayed automatically.

2
  • 1
    Use abp.ajax for errors to show as popups automatically.
    – aaron
    Nov 3, 2018 at 1:08
  • @aaron as in I don't even have to call the error function? That is pretty awesome thanks! Will definitely have to start using abp.ajax from now on. Nov 5, 2018 at 15:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.