I'm working on a MVC App and I need to check if a user is registered, for that purpose I've created a model
public class Ejemplo
{
[Required(ErrorMessage="Favor especificar Username")]
[DataType(DataType.Text)]
public string usuario { get; set; }
[Required(ErrorMessage="Favor especificar password")]
[DataType(DataType.Password)]
public string password { get; set; }
}
my problem so far is that I need to send the info of the user in a JSON format via AJAX and I need to validate that the username and password info are specified, in order to accomplish that I' coded this:
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
<script src="~/Scripts/jquery-1.10.2.js"></script>
<script src="~/Scripts/jquery.validate.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$('#myform').validate({ // initialize the plugin
rules: {
usuario: {
required: true,
minlength: 12
},
password: { required: true }
},
messages: {
usuario: {
required: "must specify username --> validate !!!",
minlength: "not a valid Lenght --> validate !!!"
},
password: {
required: "must specify a password --> validate !!!"
}
},
submitHandler:
$("#myform").on('submit', function () {
alert("have just pressed submit");
if ($("#myform").valid()) {
alert("here some code inside $.AJAX({})");
}
return false;
})
})
});
and this is my form(the code above and the form are in the same file: Index.cshtml)
<fieldset>
<legend> Validaciones MVC </legend>
@using (Html.BeginForm("Prueba", "Prueba", FormMethod.Post, new { @id = "myform" }))
{
@Html.LabelFor(M => M.usuario);
<br />
@Html.EditorFor(M=>M.usuario)
@Html.ValidationMessageFor(M => M.usuario);
<br />
@Html.LabelFor(M=>M.password)
<br />
@Html.EditorFor(M=>M.password);
@Html.ValidationMessageFor(M=>M.password)
<br />
<br />
<input type="submit" id="boton_id" name="boton_name" value="Enviar" />
}
</fieldset>
but it doesn't validate and doesn't show any message in case the username and password are empty, it only shows this alert: alert("have just pressed submit"); but never shows the second alert: alert("here some code inside $.AJAX({})"); this two alert are in
submitHandler:
$("#myform").on('submit', function () {
alert("have just pressed submit");
if ($("#myform").valid()) {
alert("here some code inside $.AJAX({})");
}
return false;
})
so, could you please help me and tell me where is my problem or what I' missing please?