Form Validation in ASP MVC - javascript

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>

Related

Validate list of codes in Javascript with an input field

I have list of codes almost 1000 codes like "PB5KE13" and i have to check these codes through input field. If the input value have a code then show Ok message. Is there anything I can get through Javascript. I don't want these in PHP or Database. I can't use these. Only HTML and Javascript.
I know the if else condition. but with this large list may be i can't use.
<form method="POST" action="" onsubmit="return checkForm(this);">
<input type="text" name="inputfield" value="">
<input type="submit" value="validate">
</form>
<script>
function checkForm(form)
{
// validation fails if the input is blank
if(form.inputfield.value == "") {
alert("Error: Input is empty!");
form.inputfield.focus();
return false;
}
}
</script>
If there is are codes to be validated, it is recommended to validate with server side script like PHP as Javascript is client side and anyone can see your code and it would not make much sense to ask for a code. But in case I misunderstood your requirement, Here is Javascript code:
let inputField = document.getElementById('#code');
let codes = ['PB5KE10','PB5KE11','PB5KE12','PB5KE13','PB5KE14']; // Can add More
function validate(val,code){
result = false;
for(let i=0;i<code.length;i++){
if(val==code[i]){
result = true;
break;
}
}
return result;
}
console.log(validate(input.value,codes)); //true if value is in array else false
Assuming you have all the codes in an array in Javascript, the only thing you need to do is use the includes() method on an array:
myKeys.includes(myInputValue);
Check out the W3Schools link for details:
https://www.w3schools.com/jsref/jsref_includes_array.asp
Hope it helps!

How to detect whether Data Annotations validations were unsuccessful?

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.

Google reCaptcha v2 - check captcha is completed before form submission

What is the best practice in checking a user has actually completed the captcha before form submission?
From the documentation I can see there is 2 callback functions data-callback and data-expired-callback.
The plan is to manipulate a boolean javascript variable setting to true/false on successful completion or on expiration and then check that the variable is true before form submission.
From a user perspective this will ensure that the user fills out the captcha before submission.
Malicious users could overwrite the javascript variable but the server side captcha validation will protect against this.
First in your form you have to put onsubmit="return check()". That means when you're submiting the form, before sending datas it will execute the function named check(). If the function returns false the form won't submit. It will look like this :
<form action="page.php" method="POST" name="form" onsubmit="return checkCaptcha ()">
Then you have your function :
<script language="javascript">
function checkCaptcha ()
{
var captcha = document.getElementById('captcha ').value;
if (captcha == "" || captcha == " ")
{
alert("please fill the captcha ");
return false;
}
else
if (captcha .length != 7)
{
return false
} // and so on
else
{
// if everything is ok you can submit
return true;
}
}
</script>

Multiple Login Forms On One Page

Below I have code that is working perfectly, as a single login form. However I need 20 of these on one page and thusfar can not even get a second login form to work. The route I have been going down is simply duplicating both the html and the javascript for each new login form on the page and just changing the i.d's using a number 1...2...3 etc. Can anybody tell me why I can not get more than one login form to work on the page at any one time?
The main reason for this is I do not know how to do one login form that directs to 20 different pages. So thought this might be easier.
HTML
<input type="text" value=" Username" id="login" style="color:#888; border-radius: 25px;" onfocus="inputFocus(this)" onblur="inputBlur(this)" required>
<input type="text" value=" Password" id="password" style="color:#888; border-radius: 25px;" onfocus="inputFocus(this)" onblur="inputBlur(this)" required>
<input type="button" value="GO" id="goButton" class="gosubmit" onclick="checkLoginPass()" />
Javascript
function inputFocus(i) {
if (i.value == i.defaultValue) { i.value = ""; i.style.color = "#000"; }
}
function inputBlur(i) {
if (i.value == "") { i.value = i.defaultValue; i.style.color = "#888"; }
}
var checkLoginPass = function () {
var login = document.getElementById("login").value;
var pass = document.getElementById("password").value;
if (login === "Client1" && pass === "Client1") {
window.location.replace("/Design1/index.html");
}
else {
//do something else;
}
}
The problem you're having is that in your javascript, you're only checking the values of the first set of fields. This will always be the case as long as you're doing it this way. And as others have said in their comments, having the passwords just sitting there in plaintext in the javascript is incredibly insecure, as anyone can just look at the js source code, identify username/password combinations, and log in.
The correct way to handle user logins is to have a single form with username and password, and then to pass those fields to the server via standard form submission. i.e. (incredibly simplified for brevity):
<form method='post' action='handlelogin.php'>
Username: <input type='text' name='username' id='username' /><br />
Password: <input type='password' name='password' id='password' /><br />
<input type='submit' value='Log In' onclick="return [some function that verifies both fields have been entered]()" />
</form>
You then validate the username/password combinations on the server, within handlelogin.php and ideally based on database values, and from there you redirect the user based on their credentials. If the user/pass are invalid, you send them back to the login page and display an appropriate error. If the credentials are valid, you set a cookie with an encrypted value to indicate that they're logged in and as whom, and then put them where they need to go.
Having 20 different login forms that are all validated in client-side javascript might actually be the worst way to handle user login ever conceived. Don't do that.
As others have said this storing username and password combos in your JavaScript source is a bad idea. But I'd like to show you how you can use arrays to store Key -> Value pairs and reference them to reduce the amount of code duplication.
In JavaScript you can define an array like so:
var _CONFIG = {
"Client1": {
"Password": "Client1",
"Redirect": "/Design1/index.html"
},
"Client2": {
"Password": "Client2",
"Redirect": "/Design2/index.html"
}
};
^ In this example your username is the Key and the Value is another array containing your password and a path to redirect to.
You can then rewrite your function to check if a Key is present in the array by using _CONFIG[login] !== undefined, in this case login is a variable containing the Key you want to look up. Then use the array stored under that Key to provide some Values to use in your code.
function checkLoginPass() {
var login = document.getElementById("login").value;
var pass = document.getElementById("password").value;
if ( _CONFIG[login] !== undefined && _CONFIG[login]["Password"] == pass) {
window.location.replace(_CONFIG[login]["Redirect"]);
}
else {
//do something else;
}
}
^ Here is your login checking function rewritten to use the array I defined.
JSFiddle Example
As I said at the beginning I don't suggest that you actually use this example as it's extremely simple for someone to bypass.
Instead logins should be dealt with using a Server Side scripting technology (e.g PHP) or using the built in HTTP Basic Authentication as suggested to you in the comments.

Covering all the bases with Form Validation, Client/Server - What is best way?

I know there are many methods of validating forms on both client and server side but I was wondering what was the best practice?
Currently, I have Javascript functions validating form input fields 'on the fly' with onkeyup/onblur functions like so:
(Partial code:)
<p class="form-registerUserName">
<div class="upperLabel">
<label for="registerUserName">User Name</label>
<span class="required">*</span>
</div>
<input
id="registerUserName"
name="registerUserName"
type="text"
size="24"
maxlength="24"
value="<?php echo $_SESSION['registerUserName'];?>"
onkeyup="validateName()"
onblur="checkDuplicateName(); validateName()"
>
<label for="registerUserName" class="hint" id="registerUserNameHint"></label>
</p>
With Javascript functions like:
function validateName() {
userName = document.getElementById("registerUserName").value.trim();
re = /^[a-zA-Z0-9_]{1,30}$/;
if (userName==="") {
document.getElementById('registerUserName').style.borderColor="red";
document.getElementById('registerUserNameHint').innerHTML = 'required';
} else if (!re.test(userName)) {
document.getElementById('registerUserName').style.borderColor="red";
document.getElementById('registerUserNameHint').innerHTML = 'only alphanumeric characters and _';
} else {
document.getElementById("registerUserName").setAttribute("style","border-color: rgb(221,221,221) rgb(241,241,241) rgb(241,241,241) rgb(221,221,221);");
document.getElementById('registerUserNameHint').innerHTML = '';
}
} //validateName()
..So that the input box turns red and shows a hint on the side of the box if it does not validate.
So my question was - What is the best way to prevent the form from submission to my (Mysqli) database when the user hits submit?
(and second question..) Do I run an additional php server-side script after client-side validation has cleared?
Some ways I imagined to accomplish this is by having my Javascript functions set a Session variable that indicates an error condition, and not allow a submit if there was.
I am not certain how to do that, or how I set up my 'submit' to not work unless the error condition was cleared.
Would appreciate any help on that.
Then do I re-validate the same data (in the same manner) with php again, after a successful client-side validation before inserting into my database?
Thanks in advance.
First off, always do server-side validation!
Second, HTML5 form validation is well supported.
Examples: http://html5pattern.com/
You can then use CSS for validation styling.
Structure your validation with this logic:
if validateName() {
document.getElementById("myForm").submit();
}
// if returns true (passed validation) then submit
//validate on click of submit button or on submit
function validateName() {
userName = document.getElementById("registerUserName").value.trim();
re = /^[a-zA-Z0-9_]{1,30}$/;
if (userName==="") {
document.getElementById('registerUserName').style.borderColor="red";
document.getElementById('registerUserNameHint').innerHTML = 'required';
**return false;**
} else if (!re.test(userName)) {
document.getElementById('registerUserName').style.borderColor="red";
document.getElementById('registerUserNameHint').innerHTML = 'only alphanumeric characters and _';
**return false;**
........ so forth
else {
return true;
}

Categories