0

Model code

[Required(ErrorMessage = "Required.")]
[EmailAddress(ErrorMessage = "Invalid email address.")]
[Remote("checkEmailAvailability", "Users", "Users", AdditionalFields = "RoleId,UserID", ErrorMessage = "Email address already in use")]
public string stEmail { get; set; }

View code

@Html.TextBoxFor(model => model.stEmail, null, new { @class = "form-control" })

<script src="@Url.Content("~/assets/global/plugins/jquery.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/assets/global/plugins/jquery-validation/js/jquery.validate.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Areas/Users/Scripts/AddPatients.js")" type="text/javascript"></script>

Js Code [ AddPatients.js ]

$("#btnAddPatient").click(function (event) {
    event.preventDefault();
    var $form = $('#frmAddPatient');
    if ($form.valid()) {//some code
    }
    }
});

Controller Code

[HttpPost]
public JsonResult updatePatient(AddEditPatientViewModel foPatientViewModel)
{
 if (ModelState.IsValid)
  {
    //some code
  }
}

What issue i am facing is that when user enters 'abc@gmail' in email address textbox it is getting pass from '$form.valid()' but 'ModelState.IsValid' is returning false ["Invalid email address."] for that same value, so user is not able to post the form.

So can anyone tell me whats wrong in my code or any solution for this?
Thanks in advance.

Akshay Chawla
  • 613
  • 1
  • 8
  • 16
  • 1
    Note that jQuery `valid()` method may uses different regex for email address compared with `EmailAddressAttribute`. Check https://stackoverflow.com/questions/2383669/how-to-create-custom-validation-attribute-for-mvc/5954452#5954452 to create custom validation attribute to accept email address input without include TLDs. – Tetsuya Yamamoto May 24 '17 at 10:04
  • @TetsuyaYamamoto is correct. You'll need to change the behaviour of either jQuery's validation or the `EmailAddressAttribute`. See more information about the issue [here](https://stackoverflow.com/questions/37610086/emailattribute-is-not-validating-correctly-in-a-viewmodel-from-asp-net-core/38386015#38386015). – Will Ray May 26 '17 at 05:56

1 Answers1

1

Try Html.EditorFor helper method instead of Html.TextBoxFor. Hope to help, my friend :))

Tomato32
  • 2,145
  • 1
  • 10
  • 10