Javascript Validation in asp.net MVC3 - javascript

My problem is when page is loaded first time,alert(1) and alert(2) pops up, but when I click on my save button alert(3) don't pops up but validation message is shown(doesn't meter if I fill correct or wrong my dropdownlist)and everything is saved.
I have this kind of JS:
<script src="#Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
alert(1);
PassWayValidators();
$('#documents_TravelDocumentDocumentPass_PassDate').datepicker();
});
function PassWayValidators() {
alert(2);
$.validator.addMethod('PassWayValidator',
function (value, element) {
alert(3);
}, 'Please Inert Valid Numbers');
$("#documents_TravelDocumentDocumentPass_PassWayId").rules("add", {
PassWayValidator: true
});
}
</script>
<...Some Code Here...>
<div class="TravelDocumentDocumentPassCommentInner">
<span>გადაცემის ფორმა
<br />
#Html.DropDownListFor(model => documents.TravelDocumentDocumentPass.PassWayId, (IEnumerable<SelectListItem>)ViewBag.DocumentPassTypeList, String.Empty, isDisabled)
#Html.ValidationMessageFor(model => documents.TravelDocumentDocumentPass.PassWayId, "*")
</span>
</div>
<...Some Code Here too... and>
#Html.ValidationSummary()
Can anyone tell me what is the problem ?

Since you're writing a custom validator, I see two things right off the bat that needs to be corrected.
First, you need to call PassWayValidators(); outside of $(document).ready(). I'm not 100% sure that it is necessary, but I think that is the only way I was able to get custom validation to work.
PassWayValidators();
$(document).ready(function () {
$('#documents_TravelDocumentDocumentPass_PassDate').datepicker();
});
Then, you need to configure your dropdown to make sure it calls your validation function with by specifying certain html attributes.
#Html.DropDownListFor(model =>
documents.TravelDocumentDocumentPass.PassWayId,
(IEnumerable<SelectListItem>)ViewBag.DocumentPassTypeList,
String.Empty,
new {
data_val = "true",
data_val_PassWayValidator = "Please insert valid numbers"
})
Something like that. I don't know what rules("add" { }) is for, but I'm not sure if you need that. In case I missed something, here is a complete sample taken from one of my applications.
<!-- some form and other html and stuff -->
#Html.TextBox("Amount", null, new
{
data_val = "true",
data_val_required = "This field is required",
data_val_number = "The field must be a number",
data_val_notBeZero = "Value must not be zero"
})
<script type="text/javascript" src="#Url.Content("~/Scripts/jquery.validate.min.js")"></script>
<script type="text/javascript" src="#Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")"></script>
<script type="text/javascript">
// validators
$.validator.addMethod("notBeZero", function (value, element)
{
if (Number(Math.abs(value).toFixed(2)) == 0)
{
return false;
}
return true;
}, "Value must not be zero");
$.validator.unobtrusive.adapters.addBool("notBeZero");
</script>

Related

Unable to execute scripts depending on Thymeleaf variables <script th:inline="javascript">

I have 2 simple scripts and 2 Thymeleaf variables, I want one script to be executed if thymeleaf variable is true, then again if other variable is true - related script to be executed and so on. But I get the following result - if one variable is true and script executed then second script won't be execudet even if second variable is true. So shortly, only one of scripts is executed, but need both (in sequence, not the same time). Here is the code:
<script th:inline="javascript">
var flag = [[${invalidInput}]]; //Thymleaf variable
window.onload = function() {
if(!flag)
return;
openForm();
};
</script>
<script th:inline="javascript">
var flag = [[${exists}]];
window.onload = function() {
if(!flag)
return;
openForm();
};
</script>
<!-- MODAL -->
<div class="form-popup" id="myForm">
<form id="registration" th:action="#{/registrate}" th:object="${newUser}" method="post" class="form-container">
<h1>Registration</h1>
<div class="alert" th:if="${exists}">
User already exists! Please try again.
</div>
<div class="invalidInput" th:if="${invalidInput}">
Username or password too short.
</div>
************************************************************
<script>
function openForm() {
document.getElementById("myForm").style.display = "block";
}
#PostMapping("/registrate")
public String login (#ModelAttribute(value = "newUser") User newUser, BindingResult bindingResult, Model model) {
userValidator.validate(newUser, bindingResult);
if(usrService.isUserPresent(newUser.getUsername())){
model.addAttribute("exists",true);
return "login";
}
else if(bindingResult.hasErrors()){
model.addAttribute("invalidInput",true);
return "login";
}
I don't think you can set the window.onload variable twice... one will simply overwrite the other. You can either combine your logic like this:
<script th:inline="javascript">
var invalidInput = [[${invalidInput}]]; //Thymleaf variable
var exists = [[${exists}]];
window.onload = function() {
if(invalidInput) {
openForm();
} else if (exists) {
openForm();
}
};
</script>
Or alternatively you could use something like jQuery, which has this functionality built in for you.
https://api.jquery.com/ready/
When multiple functions are added via successive calls to this method,
they run when the DOM is ready in the order in which they are added.

Got error while try to use intl-tel-input liberary for country code

I want to validate mobile number worldwide,so i have search a lot and finally get intl-tel-input library to perform this task easily.
i m using this from GitHub, all thing work fine.
Problem is that i m not getting auto Country Code based on user ip address in my project but when i use it individually it works.
i m sharing all thing that i have done.
i m working on
-MVC Asp
Here is the screenshot that i actually want.
https://imgur.com/TWjdrVH
Here is the screenshot that i got yet
https://imgur.com/Yr7MYBx
Error i got
Firefox
The script from “https://ipinfo.io/?callback=jQuery112405092049163202047_1555700688067&_=1555700688068” was loaded even though its MIME type (“text/html”) is not a valid JavaScript MIME type.[Learn More] Register
Loading failed for the with source “https://ipinfo.io/?callback=jQuery112405092049163202047_1555700688067&_=1555700688068”. Register:1:1
https://imgur.com/Q98ypO7
Chrome
GET https://ipinfo.io/?callback=jQuery112403105878441128118_1555701843619&_=1555701843620 net::ERR_ABORTED 429
https://imgur.com/whH2rVr
Here is some code that i used
View
#Html.EditorFor(model => model.user_mobile, new { htmlAttributes = new { #class = "form-control", id = "mobile" } })
Scripts
<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="~/Scripts/jquery.validate.min.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
<!-- Include all compiled plugins (below), or include individual files as needed -->
<script src="~/js/bootstrap.min.js"></script>
<!-- Multi select -->
<script src="~/js/multi_select.js"></script>
<!-- Select 2-->
<script src="~/js/select2/select2.full.min.js"></script>
<!-- Custom JS File -->
<script src="~/js/custom.js"></script>
<script src="~/Scripts/validation/phone/intlTelInput.js"></script>
<script type="text/javascript">
var input = document.querySelector("#mobile");
window.intlTelInput(input, {
initialCountry: "auto",
geoIpLookup: function (callback) {
$.get('https://ipinfo.io', function () { }, "jsonp").always(function (resp) {
var countryCode = (resp && resp.country) ? resp.country : "";
callback(countryCode);
});
},
//utilsScript: "build/js/utils.js" // just for formatting/placeholders etc
});
$(function () {
$('.multiselect-ui').multiselect({
includeSelectAllOption: true
});
});
// Select 2 searchable
$(function () {
//Initialize Select2 Elements
$('.select2').select2()
});
</script>
Help me out to solve my problem
i want to get auto country code based on user ip address
You need to replace url with token:
be like: https://ipinfo.io -> https://ipinfo.io?token=$Your_token
You need to register at https://ipinfo.io/ at get your token.

JQuery not working through Google's CDN

For a few hours I've been trying to understand what's wrong. My purpose is to enable a button after textfields are filled. Code seems fine according to my test at JSFiddle but it's still not working on my server. Am'I missing something or is this a server problem (which is hard to believe since javascript is client-side)?
PS: I'm not expert at HTML, so I don't know how to identate it's syntax; if it's not that readable I'm sorry and would appreciate an edit-help. thanks.
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="stylesheet" href="css/style.css">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript">
var $input = $('input:text'),
$apply = $('#apply');
$apply.attr('disabled', true);
$input.keyup(function() {
var trigger = false;
$input.each(function() {
if (!$(this).val()) {
trigger = true;
}
});
trigger ? $apply.attr('disabled', true) : $apply.removeAttr('disabled');
});
</script>
</head>
<body>
<section class="container">
<div class="OpenKore">
<div id="absolute">
<form method="GET" action="generate.php">
<fieldset>
<legend><h1>OpenKore Automatic Config:</h1></legend>
LOGIN:
<p><input type="text" id="id_login" name="login_value" value="" placeholder="Login"></p>
SENHA:
<p><input type="text" id= "id_senha" name="senha_value" value="" placeholder="Senha"></p>
PIN:
<p><input type="text" id="id_pin" name="pin_value" value="" placeholder="PIN"></p>
<input id="apply" type="submit" name="commit" disabled value="Gerar Configurações">
</fieldset>
</form>
</div>
</div>
</section>
</body>
</html>
When the browsers reads your HTML page, it reads top to bottom. When it gets to your <script> tags it runs them. Now it us doing this before it has got to the rest of the page, i.e. before it even knows about any body or form or input:text tags, so even though you code will run, it will simply not do anything because none of the elements on the page exist yet.
JavaScript 101, make the code run after the page has loaded, if you need to access elements on the page. How do you do that? either put the code at the bottom of the page (move your <script> tags to just before the </body> tag), or wrap your code in a function that is executed after the browser has finished loading the page. Now jQuery has a very helpful way of doing this for you, pass a function to jQuery and it will be executed after the page is loaded.
jsFiddle does this automatically for you, hence the drop down in the top left corner saying 'onLoad'
i.e. your code
$(); //this is the jQuery function
//This is your code wrapped in a function called 'yourCode'
function yourCode() {
var $input = $('input:text'),
$apply = $('#apply');
$apply.attr('disabled', true);
$input.keyup(function () {
var trigger = false;
$input.each(function () {
if (!$(this).val()) {
trigger = true;
}
});
trigger ? $apply.attr('disabled', true) : $apply.removeAttr('disabled');
});
}
$(yourCode); //this is passing the jQuery function a function,
//this will now be execute once the page is loaded
//or what most people do, pass in as an anonymous function
//which eliminates a step
$(function () {
var $input = $('input:text'),
$apply = $('#apply');
$apply.attr('disabled', true);
$input.keyup(function () {
var trigger = false;
$input.each(function () {
if (!$(this).val()) {
trigger = true;
}
});
trigger ? $apply.attr('disabled', true) : $apply.removeAttr('disabled');
});
});
as suggested by #j08691 I would suggest reading about the document ready in jQuery here

MVC Razor Ajax Form Submit giving 'unexpexted token u'

This is a MVC VB.NET Razor application. I have a partial view which loads in the bottom of a parent view. And in that partial view I have buttons that when click fire a popup dialog modal window which has a partial view attached to it. The user is supposed to be able to edit the form then click update and the information is then posted to the controller. However I am getting the below error message on submit.
I followed the blog here to get everything wired up. When the update button is clicked there error is occuring here:
Below is the PartialView that contains the buttons and javascript that trigger the popup modal
#ModelTYPE IEnumerable(of data_manager.attendance)
<script src="#Url.Content("~/Scripts/jquery.unobtrusive-ajax.js")" type="text/javascrip</script>
<table>
<tr>
<th>Conf. Number</th>
<th>Class Title</th>
<th>Status of Class</th>
<td>Edit</td>
</tr>
#For Each x In Model
Dim currentItem = x
#<tr>
<td>#Html.DisplayFor(Function(f) currentItem.conf_number)</td>
<td>#Html.DisplayFor(Function(f) currentItem.courseTitle)</td>
#If currentItem.Completed_Class = "Completed" Then
#<td>#Html.ActionLink("Completed(Print Cert)", "Ind_Cert", "Printing", New With {.firstName = currentItem.firstName, .lastname = currentItem.lastName, .classRef = currentItem.course_ref, .cNumber = currentItem.conf_number}, Nothing)</td>
Else
#<td>#Html.DisplayFor(Function(f) currentItem.Completed_Class)</td>
End If
<td>#Html.ActionLink("Modify", "CourseHistoryEdit", New With {.id = currentItem.id}, New With {.class = "editLink"})</td>
</tr>
Next
</table>
<div id="updateDialog" title="Update Attendance"></div>
<script type="text/javascript">
var linkObj;
$(function () {
$(".editLink").button();
$('#updateDialog').dialog({
autoOpen: false,
width: 400,
resizable: false,
modal: true,
buttons: {
"Update": function () {
$("#update-message").html(''); //make sure there is nothing on the message before we continue
$("#updateAttendance").submit();
},
"Cancel": function () {
$(this).dialog("close");
}
}
});
$(".editLink").click(function () {
//change the title of the dialgo
linkObj = $(this);
var dialogDiv = $('#updateDialog');
var viewUrl = linkObj.attr('href');
$.get(viewUrl, function (data) {
dialogDiv.html(data);
//validation
var $form = $("#updateAttendance");
// Unbind existing validation
$form.unbind();
$form.data("validator", null);
// Check document for changes
$.validator.unobtrusive.parse(document);
// Re add validation with changes
$form.validate($form.data("unobtrusiveValidation").options);
//open dialog
dialogDiv.dialog('open');
});
return false;
});
});
function updateSuccess(data) {
if (data.Success == true) {
//we update the table's info
var parent = linkObj.closest("tr");
parent.find(".Completed_Class").html(data.Object.completed);
parent.find(".carDescription").html(data.Object.Description);
//now we can close the dialog
$('#updateDialog').dialog('close');
//twitter type notification
$('#commonMessage').html("Update Complete");
$('#commonMessage').delay(400).slideDown(400).delay(3000).slideUp(400);
}
else {
$("#update-message").html(data.ErrorMessage);
$("#update-message").show();
}
}
</script>
And this is the partialView that is rendered when the Modify button is clicked next to each one.
#ModelTYPE DataModels.DataModels.AjaxCourseHistoryEdit
#Using (Ajax.BeginForm("CourseHistoryEdit", "Admin", Nothing, New AjaxOptions With {.InsertionMode = InsertionMode.Replace, .HttpMethod = "POST", .OnSuccess = "updateSuccess"}, New With {.id = "updateAttendance"}))
#Html.ValidationSummary(true)
#<fieldset>
<legend>Attendance Update</legend>
#Html.HiddenFor(Function(m) Model.attendId)
<div class="editor-label">
#Html.Label("Course Title")
</div>
<div class="editor-field">
#Html.DisplayFor(Function(m) Model.courseTitle)
</div>
<div class="editor-label">
#Html.Label("Completed Status")
</div>
<div class="editor-field">
#Html.DropDownList("completed", New SelectList(ViewBag.CourseStatuses))
</div>
<div class="editor-label">
#Html.Label("Hours Completed")
</div>
<div>
#Html.EditorFor(Function(m) Model.hoursCompleted)
</div>
</fieldset>
End Using
Below are the javascript libraries that are being loaded in the _layout file for the project.
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min.js"></script>
<script src="#Url.Content("~/Scripts/jquery.unobtrusive-ajax.js")" type="text/javascript"> </script>
<script src="#Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
Any help is greatly appreciated. I have went around with this for hours and google searches have turned up several SO posts saying that Unexpected token u is related to an invalid line termination. This helps me none as I cannot find anything that remotely looks like improper html namely tags that arent closed..
I had a csharper bring up the # on the table and fieldset. This is normal in these instances for vb.net below is a screenshot of the rendered html
A comment made by Moeri pointed me in the right direction. It turned out that my model was using a integer value for the hiddenFor value. Which for reasons unknown to me the AJAX post did not like that at all. By changing the type of attendId from Integer to String and further using proper editorFor / labelFor the issue has been resolved. Maybe this will help someone that hits this stumbling block as I have.

why does this regex work outside of a javascript function but not inside of it?

Okay so I'm kind of new to regexps in general, let alone in Javascript.
I am trying to work on a form validation project and I found a site where they have a list of useful sample regexps for various things here which has a few for email validation, which is what I'm attempting at the moment.
Anyway, following this example for form validation on w3schools I was able to get it working properly using their example and the regexp works outside of the javascript function, but for some reason when I call it inside the function it returns a value of undefined.
Here's my code:
<html>
<head>
<title>formzz validate-jons</title>
<script type="text/javascript">
pattern = new RegExp("^[0-9a-zA-Z]+#[0-9a-zA-z]+[\.]{1}[0-9a-zA-Z]+[\.]?[0-9a-zA-Z]+$");
function valid8email(field, txt)
{
with(field)
{
//at_pos = value.indexOf('#');
//dot_pos = value.lastIndexOf('.');
if(!pattern.test(value)) //at_pos < 1 || (dot_pos - at_pos) < 2)
{
alert(txt);
return false;
}
else
{
return true;
}
}
}
function valid8(form)
{
with(form)
{
if(valid8email(email, "you must enter an email address") == false)
{
email.focus();
return false;
}
}
}
</script>
</head>
<body>
<form action="#" method="POST" onsubmit="return valid8(this)">
Email: <input type="text" name="email" size="30" />
<input type="submit" value="clicky-click" />
</form>
<script type="text/javascript">
alert(pattern.test(""));
</script>
</body>
</html>
Okay... so the alert in the script tags inside the body works just fine.
I've done numerous tests inside the javascript function itself and checked various things:
the type of 'value' is String
the function returns 'undefined' when called inside the javascript
the regex itself works fine as it will return true when the proper formatting is entered in the script tags below
So what could the issue be? I am confused.
The problem is that pattern refers to field.pattern (an HTML5 attribute) because you're using it inside the with(), and that's a string, not your regex. If you called it something else like pattern1, it would work fine.
That being said, don't use with in the first place, and you won't have these issues :)
The non-with version looks like this:
var pattern = new RegExp("^[0-9a-zA-Z]+#[0-9a-zA-z]+[\.]{1}[0-9a-zA-Z]+[\.]?[0-9a-zA-Z]+$");
function valid8email(field, txt) {
if (!pattern.test(field.value))
{
alert(txt);
return false;
}
else {
return true;
}
}
function valid8(form) {
if (valid8email(form.email, "you must enter an email address") == false) {
form.email.focus();
return false;
}
}
You can test it out here.

Categories

Resources