I want to have a script to validate if a field called Email is not empty. I created a script which I put in the SCRIPTS folder. But nothing is fired when we click the Create button. Any idea of what is wrong with this ? Thanks
ValidationEmail.js
$(function () {
$("SubmitBTNCreate").click, function (e) {
var email = $("#Email").val();
if (email == "") {
e.preventDefault();
alert("Please enter an email address.");
}
});
});
Create.cshmtl
@model codefirst.Models.Personne
@{
ViewBag.Title = "Create";
}
<h2>Create</h2>
@using (Html.BeginForm()) {
@Html.AntiForgeryToken()
@Html.ValidationSummary(true)
<fieldset>
<legend>Personne</legend>
<div class="editor-label">
@Html.LabelFor(model => model.Nom)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Nom)
@Html.ValidationMessageFor(model => model.Nom)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.Prenom)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Prenom)
@Html.ValidationMessageFor(model => model.Prenom)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.Email)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Email)
@Html.ValidationMessageFor(model => model.Email) <== field to check if empty
</div>
<p>
<input type="submit" value="Create" id="SubmitBTNCreate" /> <== btn submit
</p>
</fieldset>
}
<div>
@Html.ActionLink("Back to List", "Index")
</div>
@section Scripts {
@Scripts.Render("~/bundles/jqueryval")
@Scripts.Render("~/Scripts/ValidationEmail") <== calling the script
}
$.fn.jqueryto see. Other than that, see the generated html and check if the input has REALLY idEmail, because I remember working on a project which added some names to the id so the$('#Email')would not work.@Html.ValidationMessageFor(model => model.Email) <== field to check if emptyif I remember right,ValidationMessageForis not an input, it's a div with errors (if any). If you really want to test the div, change the .val()from the answers tovar email = $("#Email").empty()orvar email = $("#Email").html() === ''to return true or false@Scripts.Render("~/Scripts/ValidationEmail.js")instead? I don't have VS at work so can't test that atm. Anyways, now you know that your code does not work because you are not loading the script.