I have an ASP.NET MVC page with fields like this...
#Html.TextBoxFor(model => model.MyField, new { #class = "form-control", data_val_required = "Required field" })
Also, I have a JavaScript validation function called from the "onsubmit" event of the form...
#using (Html.BeginForm("MyAction", "MyController", FormMethod.Post, new { #onsubmit = "return validateDeep();" }))
And I need to detect whether the Data Annotation validations were successfull or not. I investigated and found the "Page_IsValid" variable, which unfortunately is always undefined.
function validateDeep()
{
var errors = "";
if (!Page_IsValid) // this fails, also this: document.Page_IsValid
errors = errors + "- There are empty fields (marked in red color)<br/>";
errors = errors + getOtherValidationErrors();
if (errors != "") {
openAlert("ERRORS!<br/>" + errors);
return false;
}
return true;
}
So, the question is... how to detect that those data-annotation validations, in the client side and before the Post, were not successful?
-- Deleted wrong answer --
My first answer was wrong, I unterstand the szenario of OP now like this:
Form is posted to the server
server returns form because ModelState.IsValid == false
page gets rendered with errors and served to client
how do I detect the existing errors on the client?
If you render the errors with #Html.ValidationSummary(), the generated markup will look like this [1]:
<span style="font-family: inherit;"><div class="validation-summary-errors" data-valmsg-summary="true">
<ul>
<li>List of error messages ...</li>
</ul>
</div>
</span>
So data-valmsg-summary="true" tells us that there have been validation errors, i.e. Data Annotation validations were unsuccessfull.
// using jQuery 1.7.2
var invalid = $('.validation-summary-errors').data('valmsg-summary');
if (invalid) {
// some javascript ...
}
Solved: The validation based on data-val-required can be evaluated with this...
var form = $("#MyForm");
if (!form.valid())
alert("You have incomplete/invalid values, please correct them");
This validation is based on the "unobtrusive" JQuery validations, not on the ASP.NET MVC Data Annotations validations.
Related
In my view i have
#using (Html.BeginForm(null,null,FormMethod.Post, new {onsubmit="return
validateForm(this);", name = "frm", id = "frm" }))
and in my JS file i have this code
function validateForm(form) {
alert("Called")
var x = form[model.username].value;
if (x == "") {
alert("Name must be filled out");
return false;
}
}
When i use just an alert in the JS, it works. However when i pass in the form, even if the username is blank, the rest of the data is submitted. Am using ASP MVC 5
any ideas please?
Let's assume that model.username contains "johndoe123". That value is then used, meaning that in fact you are requesting form["johndoe123"].value which I think is pretty unlikely to return a value. It may even produce an error, especially if either model or model.username are undefined.
You probably meant to request a form field that has name="username" or something like that, so I'll give an example on how to do that:
var form = document.getElementById("theForm");
console.log(form);
console.log(form["username"]);
console.log(form["username"].value);
<form id="theForm">
<input type="text" name="username" value="something">
</form>
I have this code:
#if (!string.IsNullOrWhiteSpace(Model.ErrorMessage))
{
<script>
$('#modalError').modal('show');
</script>
Response.Write("<script>alert('hello');</script>");
HttpContext.Current.Response.Write("<script>alert('hello');</script>");
}
Where check if Model.Error Message is different from empty, so I an alert to the user, but none of the forms submitted by the condition if this working, how can it be done?
already I tried so:
#if (!String.IsNullOrEmpty(ViewData["erro"] as string))
{
<script>alert(#ViewData["erro"]);</script>
}
This and a part of the view.
My controller this way:
public ActionResult Login(LoginViewModel model, SignInMessage message)
{
if (!String.IsNullOrEmpty(model.ErrorMessage))
ViewData["erro"] = !String.IsNullOrEmpty(model.ErrorMessage) ? model.ErrorMessage : null;
return this.View(model);
}
I want to display a javascript message because I will use the modal Bootstrap
#Alexandre Lima,
As pointed out in comments by others and I agree too, not sure if your approach is right or if it is then we need more information, that said, You have the following options
Use simple data validations on your view models to notify users of
an invalid email - this is built into MVC for you - MVC's data
annotation. Here are links
http://www.asp.net/mvc/overview/older-versions-1/models-data/performing-simple-validation-cs
From your comment, looks like you want to display something on login
failures , meaning your server code got back saying Auth failed,
if that is the case, am assuming here you have something like this
on your controller code
public ActionResult Login(LoginModel login)
{
if(ModelState.IsValid)
{
//you call your service to get back the result
if(!NotAValidUser)
{
ModelState.AddModelError("LoginFailed", "The user name and or password is incorrect.")
}
}
}
in your View
#Html.ValidationMessage("LoginFailed") // this will display the above message
If it's a View, then you might be better off using Javascript/JQuery. To do that, you'll need to add a hidden field somewhere in your HTML and set the value to Model.ErrorMessage. Like this:
<input type="hidden" id="hdError" value="#Model.ErrorMessage" />
Then at the end of your HTML body, you add the Javascript code:
<script>
$(function() {
var errorStr = $("#hdError").val();
if (errorStr) {
alert("hello"); //or any other alert message
}
});
</script>
I'm looking to create custom validation messages on my activeforms in Yii2 for the client side validation. The goal i want to achieve is to get a bootstrap popover on the side of the form field with the validation error message of that field, e.g. password too short or password does not meet the requirements. These messages change dynamicaly based on the given input and validation rules.
I've been looking at using the clientValidateAttribute and create javascripts for the fields, this is working but i'm missing out on setting the proper validation messages coming from the model validation.
This is a simple example to create a popover based on some conditions in the clientValidateAttribute.
return <<<JS
var def = $.Deferred();
if (attribute.name == "email" && value !== "") {
$( ".login-pop" ).popover("show");
} else {
$( ".login-pop" ).popover("destroy");
}
deferred.push(def);
JS;
This will show an popover on the .login-pop class field when the attribute is email and its empty. I've been looking to use the messages array, but it looks like it's only set once.
Perhaps i'm mislead with the validation and there might be easier or better solutions to achieve this goal and be able to validate per field, return the proper messages to be used in a javascript tool.
Thank you.
I'm working on designing a new process for internal job submission for work which now involves javascript for it to work effectively.
Scripting is not my forte but that hasn't deterred me, I've been able to find three different pieces of code to insert into the various buttons and fields and they've done what they should do. My problem is I need to combine some of these for an extra validation on submit. This is where I fall short.
The process:
There is a required field in the form which currently runs a custom validation script to check a certain format specific to the code needed for a job. This runs well and I was even able to add an alert and hint images that show when incorrect and a little tick when correct. Beautiful.
The second major part of the form is in the submit button. I hacked together a code which not only emails the submitted form with fields as the subject line but also makes all fields read only before doing so. Brilliant.
Here's the messy part. A user can enter a correct or incorrect required code and the validator does its bit but that doesn't stop them from still submitting the form. Fine. I can fix that by running the validator again on the submit button so it not only gives user feedback on blur of the required field but again validates on submit so if the field is incorrect the submit stops until the user has the correct value in the field. This is where my knowledge stops like a cliff edge and I can't seem to build a bridge.
I've tried numerous ways of calling the field value then just running the same validation script with some if and else statements but it just doesn't work.
Can anyone help? Current code for submission button below but keep in mind that the validation section of this code is also attached to the required field directly (this affects it?):
function OR_Stuff() {
var ProjectTitle = getField("ProjectTitle").value;
var Brand = getField("Brand").value;
var Name = getField("Name").value;
var Noosh = getField("INT_NooshCode").value;
for (var i = 0 ; i < this.numFields ; i++) {
var f = this.getField(this.getNthFieldName(i));
if (f.type != "Submit") // Change f.type to button name in form that the action is applied to
{
f.readonly = true;
}
}
this.mailDoc({
cTo: "email",
cBcc: "email",
cSubject: "NEW JOB: "+Brand+" - "+ProjectTitle+" - "+Noosh,
cMsg: "Thanks "+Name+" for sending through this job."
});
}
var re = /^\d{5}[A-Z]\d{2}$/
if (re.test(INT_NooshCode.value) == false) {
this.getField("RequiredAlert").display = display.visible;
this.getField("NooshTick").display = display.hidden;
app.alert("Sorry, we can't start a project without a Noosh code. \n\nPlease enter a valid Noosh code EG: 34256P02");
}
else {
OR_Stuff();
}
Sorry for this most likely simple question.
I am running a script on submission of the form (code below), but first I would like to validate the form (contains one text box which must be an email) before the code is executed.
The script below is taken from here to ensure the form data is passed along to the colorbox lightbox script. But i only want to run this if the form is validated. I don't know how to combine this with an email validation script. Help! At the moment i've got a script that validates email (dreamweaver's) and this running, this command still runs even if it doesn't validate and i am not sure how to edit it so it doesn't.
$(document).ready(function() {
$("input#SearchButton").colorbox({href: function(){
var url = $(this).parents('form').attr('action');
var ser = $(this).parents('form').serialize(); //alert(url+'?'+ser);
return url+'?'+ser;
}, innerWidth:"1280", innerHeight:"884px", iframe:true, scrolling:false});
});
Then I am using this to validate the form:
function MM_validateForm() { //v4.0
if (document.getElementById){
var i,p,q,nm,test,num,min,max,errors='',args=MM_validateForm.arguments;
for (i=0; i<(args.length-2); i+=3) { test=args[i+2]; val=document.getElementById(args[i]);
if (val) { nm=val.name; if ((val=val.value)!="") {
if (test.indexOf('isEmail')!=-1) { p=val.indexOf('#');
if (p<1 || p==(val.length-1)) errors+='- '+nm+' must contain an e-mail address.\n';
} else if (test!='R') { num = parseFloat(val);
if (isNaN(val)) errors+='- '+nm+' must contain a number.\n';
if (test.indexOf('inRange') != -1) { p=test.indexOf(':');
min=test.substring(8,p); max=test.substring(p+1);
if (num<min || max<num) errors+='- '+nm+' must contain a number between '+min+' and '+max+'.\n';
} }} else if (test.charAt(0) == 'R') errors += '- '+nm+' is required.\n'; }
} if (errors) alert('The following error(s) occurred:\n'+errors);
document.MM_returnValue = (errors == '');
} }
Thanks!!!!
The HTML for the tigger is:
<input name="submit" type="image" onclick="MM_validateForm('email','','RisEmail');return document.MM_returnValue" src="images/go-button.gif" alt="Go! Get quote now!" align="top" : id="SearchButton"/>
In a nutshell: I want to tigger the code in the first snippet if the form validates using the code in the second snippet that is called by the html even in the third code snippet, but not if it doesn't.
You didn't post your HTML so I don't know if you have an actual form or just an input field without an actual form tag.
Assuming the former, you need a submit event so you can validate the form and then, if validation failed, terminate the submission.
$('#my_form').submit(function() {
//validate - forget the whole thing if it fails
if (!$('#my_field').val()) return false;
//if we get this far, validation succeeded - do other stuff now
});
A form submission is halted any time the submit callback returns false (or fires event.preventDefault()).
Andrew is correct, it would help if you provided the html in order to establish what the event trigger will be. Having reviewed the jquery plugin 'colorbox' briefly, it appears the lightbox is bound to the selectors click event.
Assuming Andrew's answer, if the email address validates you would need to manually trigger the click event for the lightbox from within the submit handler for the form. The following code should suffice.
$('#my_form').on('submit', function(e){
//perform validation.
MM_validateForm('email','','RisEmail');
//check the document variable set by the validation.
if (!document.MM_returnValue)
{
//did not validate
}else{
//open the colorbox
var search_btn = $('input#search');
search_btn.colorbox({href: function(){
var url = $(this).parents('form').attr('action');
var ser = $(this).parents('form').serialize();
return url + '?' + ser;
},
innerWidth: "1280",
innerHeight: "884px",
iframe:true,
scrolling:false});
//manually trigger the click event
search_btn.trigger('click');
}
//in either instance, disable the default action to ensure the form does not follow through.
e.preventDefault();
});
Obviously you'll have to replace the css selector names with your own, and utilise the email validation script that you may or may not have.