How to override form validation using JavaScript - javascript

How do I write a function that overrides form validation when a user clicks the back button?
If the user doesn't fill the form and clicks submit, it tells shows " please fill in this field"
then I added a back button in case the user doesn't wanna fill the form and wants to go back
but onClick it shows "please fill in this field"
how do I override this when the user clicks back?
function validateForm() {
var x = document.forms["myForm"]["fname"].value;
if (x == "") {
alert("Name must be filled out");
return false;
}
}
function goBack() {
window.history.back()
}
<div class="form-div">
<form name="myForm" action="action_page.php" onsubmit="return validateForm()" method="post" required>
<button onclick="goBack()">Go Back</button>
<div class="container">
<h1>Register</h1>
<p>Please fill in this form to create an account.</p>
<hr>
<label for="name"><b>FullName</b></label>
<i class="fa fa-user icon"></i>
<input type="text" placeholder="Enter Name" name="fullName" id="name" required>
<label for="email"><b>Email</b></label>
<i class="fa fa-envelope icon"></i>
<input type="text" placeholder="Enter Email" name="email" id="email" required>
<label for="psw"><b>Password</b></label>
<i class="fa fa-key icon"></i>
<input type="password" placeholder="Password" id="psw" name="psw" pattern="(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,}" title="Must contain at least one number and one uppercase and lowercase letter, and at least 8 or more characters" required>
<label for="psw-repeat"><b>Repeat Password</b></label>
<i class="fa fa-key icon"></i>
<input type="password" placeholder="Repeat Password" name="psw-repeat" id="psw-repeat" required>
<p>By creating an account you agree to our Terms & Privacy.</p>
<button type="submit" class="registerbtn">Register</button>
</div>
<div class="container signin">
<p>Already have an account? Sign in.</p>
</div>
</form>
</div>

I think removing the "required" attribute from your form tag should be good even if you keep this "required" attribute on your inputs.

This thing happen because you added button inside <form> that causing it to act as a submit button
see this: How to prevent buttons from submitting forms
so basically you can return false, but its much easer to just remove the button outside the <form>
FYI
You should ALWAYS check the values of the inputs buy yourself because everyone who is familiar with the devTools can delete the required attribute and then send empty values to your server
Another FYI
You must check the values also in the server because there are many ways you can override the client checks (you do the client side check just for UX)

Related

JavaScript validation of html form

I have a PHP file containing a HTML registration form. The form consists of a few fields including a phone number, password and repeat password field.
I would like these fields to be validated and require some guidance on how to validate the users input. These fields should be required and the two password fields should match.
If it fails validation I would like the user to have feedback and the form to be prevented from being submitted.
If it passes then the form should be submitted.
<div id="id02" class="modal">
<form class="modal-content animate" action="register.php" method="post">
<div class="imgcontainer">
<span onclick="document.getElementById('id02').style.display='none'" class="close" title="Close Modal">×</span>
</div>
<div class="container">
<label><b>Name:</b></label>
<input type="text" placeholder="Enter Name" name="name" required>
<label><b>Phone No.:</b></label>
<input type="text" placeholder="Enter Phone number" name="phone" required>
<label><b>Date of Birth:</b></label>
<input type="date" placeholder="Enter Date of Birth" name="dob" required>
<label><b>E-mail:</b></label>
<input type="text" placeholder="Enter Email" name="email" required>
<label><b>Password:</b></label>
<input type="password" placeholder="Enter Password" name="psw" required>
<label><b>Repeat Password:</b></label>
<input type="password" placeholder="Repeat Password" name="psw-repeat" required>
<input type="checkbox" checked="checked"> Remember me
<p>By creating an account you agree to our Terms & Privacy.</p>
<div class="clearfix">
<button type="submit" class="register">Register</button>
<button type="button" onclick="document.getElementById('id02').style.display='none'" class="cancelbtn">Cancel</button>
</div>
</div>
</form>
<script>
// Get the modal
var modal = document.getElementById('id02');
// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event)
{
if (event.target == modal)
{
modal.style.display = "none";
}
}
</script>
Taken from https://www.w3schools.com/js/js_validation.asp (one of the first google results when googling for your question. You might want to do so yourself the next time).
You might want to adapt your code like this:
<form class="modal-content animate" action="register.php" onsubmit="return validateForm()" name="formToValidate" method="post">
[...] your other code [...]
function validateForm() {
// get value of phone number field
var x = document.forms["formToValidate"]["phone"].value;
// check phone number for being empty
if (x == "") {
alert("Phone number must be filled in");
// return false to interupt the POST request.
return false;
}
// copy, paste and adapt for the other form elements
}

How to remove password saved by remember me option by browser using Angular.js and Javascript

I have one issue in my password field and user name field using Angular.js.I have a login page.Suppose user clicked on remember me option of browser after the login.These saved user name and password is displaying on my username field and password field.I am explaining my code below.
<div class="input-group bmargindiv1 col-md-12">
<span class="input-group-addon ndrftextwidth text-right" style="width:180px">User Name :</span>
<div ng-class="{ 'myError': billdata.uname.$touched && billdata.uname.$invalid }">
<input type="text" name="uname" id="uname" class="form-control" placeholder="add user Name" ng-model="login_name" ng-minlength="6" ng-keypress="clearField('uname');" tabindex="6" >
</div>
</div>
<div class="help-block" ng-messages="billdata.uname.$error" ng-if="billdata.uname.$touched">
<p ng-message="minlength" style="color:#F00;">This field is too short.The min length of your user name should be 6.</p>
</div>
<div class="input-group bmargindiv1 col-md-12" ng-hide="showpass">
<span style="position:absolute; right:5px; margin-top:6px; top:0px;"><button class="btn btn-xs btn-success"ng-mousedown="hideShowPassword();" ng-mouseup="hideShowPassword();" ng-mouseleave="hidePassAfterLeave();" ><i class="fa fa-eye"></i></button></span>
<span class="input-group-addon ndrftextwidth text-right" style="width:180px">Password :</span>
<div ng-class="{ 'myError': billdata.pass.$touched && billdata.pass.$invalid }">
<input type="{{inputType}}" name="pass" id="passno" class="form-control" placeholder="password" ng-model="password" ng-minlength="8" ng-pattern="/^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[_!##\$%\^&\*])(?=.{8,})/" ng-keypress="clearField('passno');" tabindex="7" >
</div>
The Login credentials used by user at the time of login is available where ever the username and password filed is found which i dont need.Here I need blank user name and password field even the user clicked remember me option of browser.Please help me to resolve this issue .
Try to add 2 hidden inputs to start of your form:
<form autocomplete="off">
<div style="display: none;">
<input type="text" id="PreventChromeAutocomplete"
name="PreventChromeAutocomplete" autocomplete="username" />
<input type="password" id="PreventChromePasswordAutocomplete"
name="PreventChromePasswordAutocomplete" autocomplete="password" />
</div>
<!-- Rest form -->
</form>
you can try this
<input type="password" autocomplete="off" />
try adding autocomplete="off" on your form also
<form autocomplete="off" ...></form>
Try using javascript as :
$('#passno').attr("autocomplete", "off");
or add (autocomplete="off") attribute in html input tag :
For more info, refer http://www.w3schools.com/tags/att_input_autocomplete.asp
Try same for username field as well. :)

AngularJs $error.minlength value before type

I'm using $error.minlength in cell phone input but when I want to validate this input for enabling the button to send a form to the server, $error.minlenght value is null. It shows me nothing until I type something but I need to know before I type anything how to tell angular that my $error.minlength is false;
so I can use this in disable attribute and check the validation of the each input for whole form then Enable the button and send the form to the server.
<input required name="mobileNo" ng-minlength="11" minlength="11" maxlength="11" ng-class="{nessasery:signupForm.mobileNo.$invalid,blur:signupForm.mobileNo.$touched && signupForm.mobileNo.$invalid}" class="form-control" id="tel" type="text" ng-pattern="/^09[0-9]*$/" ng-model="account.mobileno" placeholder="cellphone"/>
<span class="msg text-danger" ng-show="signupForm.mobileNo.$touched">
<span ng-show="signupForm.mobileNo.$error.required">can't leave this field</span>
</span>
<span class="msg text-danger" ng-show="signupForm.mobileNo.$dirty">
<span class="msg text-danger" ng-show="signupForm.mobileNo.$error.minlength">Total Number Of Phone Number is 11</span>
<span class="msg text-danger" ng-show="signupForm.mobileNo.$error.pattern">Enter Valid Phone Number</span>
</span>
<button ng-disabled="(signupForm.mobileNo.$error.minlength)">Singup</button>
in angularJS when we need to Validate the form and Enable the button (singup button) , we have two options:
validate the each input of the form or just validate the form element itself.
like This:
[formname].$invalid
<form name="myForm" novalidate >
<input name="username" required/>
<input name="password" required />
<button type="submit" ng-disable="myForm.username.$invalid && myForm.password.$invalid">sinup<button/>
<form/>
<!-- it,s better to do this: -->
<button ng-disable="myForm.$invalid">

Bootstrap reset button onclick keep textbox as valid

I have used below code for bootstrap textbox and textarea and also in the last div I have used button type="reset" .But when I entered invalid shop name and valid Address and click on Reset button it reset it and after only entering invalid shop name and click on Add shop then it is successfully adding new shop.Both the textbox show green background-color and correct sign even after it is empty.
Please help me.
Please see below image after onclick of reset button:
<form id="defaultForm" method="post" class="form-horizontal"
data-bv-message="This value is not valid"
data-bv-feedbackicons-valid="glyphicon glyphicon-ok"
data-bv-feedbackicons-invalid="glyphicon glyphicon-remove"
data-bv-feedbackicons-validating="glyphicon glyphicon-refresh">
<div class="form-group">
<label class="col-xs-3 control-label">Shop Name</label>
<div class="col-xs-4">
<input type="text" class="form-control" pattern="^[a-zA-Z\s]+$"
data-bv-regexp-message="The shop name can consist of alphabetical characters only" name="shopName" placeholder="Shop Name" data-bv-trigger="blur" data-bv-notempty="true" data-bv-notempty-message="Shop name is required and cannot be empty" />
</div>
</div>
<div class="form-group">
<label class="col-xs-3 control-label">Shop Address</label>
<div class="col-xs-4">
<textarea id="id_txt_addr" type="text" class="form-control" name="shop_address" placeholder="Shop Address" style="height:100px" maxlength="200" data-bv-trigger="blur" data-bv-notempty="true" data-bv-notempty-message="Shop address is required and cannot be empty"></textarea>
</div>
</div>
<div class="form-group">
<div class="col-xs-9 col-xs-offset-3">
<input type="submit" name="add" class="btn btn-primary" value="Add Shop">
<button type="reset" class="btn btn-default">Reset</button>
</div>
</div>
</form>
On reset button click, remove all relevant validation classes and elements handling error message inside closest form. Here an example:
$(':reset').on('click', function(){
var $form = $(this).closest("form");
$form.find('*').removeClass('has-success has-error glyphicon-ok glyphicon-remove');
$form.find('.help-block').remove();
});
-DEMO-
Now maybe there is a bootstrap method to reset validation, you should check bootstrap DOC maybe.
$(document).ready(function () {
$("#ibtReset").on("click", function () {
$('#ShopName').val("");
$('#id_txt_addr').val("");
$('.glyphicon ').remove();
});
});
On reset button click both the values become empty.
It may help You.

Watin - Submit button remain disabled after filling form

I have a website which I need to login to automatically.
I am trying to use Watin .NET library in order to do that.
When I fill out the user name and password fields using Watin, the sumbit button remains disabled.
I tried applying many events on the other fields (KeyPress, KeyDown, KeyUp, Tab, Enter...) Nothing worked.
Pardon me for finding the button by value, but this is the only way that I found that worked.
var field = ie.TextField(Find.ByName("userName"));
field.TypeText("username");
field.KeyDown();
field.KeyUp();
field = ie.TextField(Find.ByName("password"));
field.TypeText("pwd");
field.KeyDown();
field.KeyUp();
ie.Button(Find.ByValue("התחבר")).Click();
I am getting an exception that the button is disabled.
The page which I need to login to is:
https://portal.dorad.co.il/#/Login
All that I want is to find an automatic way to make the sumbit button enabled so that I can login.
Login Form Code:
<form class="span5 offset4 loginForm ng-pristine ng-invalid ng-invalid-required" name="loginForm" ng-submit="doLogin()" autocomplete="off">
<h2>
Login
</h2>
<fieldset>
<div class="control-group">
<label class="control-label" for="fullName">
User Name
</label>
<div class="controls">
<input name="userName" id="useName" ng-required="true" type="text" ng-model="user.userName" auto-fill-sync="" autocomplete="off" class="ng-pristine ng-invalid ng-invalid-required" required="required">
<span class="alert alert-error" ng-show="loginForm.userName.$error.required && loginForm.userName.$dirty" style="display: none;">
Mandatory Field
</span>
</div>
</div>
<div class="control-group">
<label class="control-label" for="emailAddress">
Password
</label>
<div class="controls">
<input name="password" id="password" type="password" ng-model="user.password" auto-fill-sync="" ng-required="true" autocomplete="off" class="ng-pristine ng-invalid ng-invalid-required" required="required">
<span class="alert alert-error" ng-show="loginForm.password.$error.required && loginForm.password.$dirty" style="display: none;">
Mandatory Field
</span>
</div>
</div>
</fieldset>
<input type="submit" class="btn" value="התחבר" ng-disabled="loginForm.$invalid" disabled="disabled">
</form>
This might be due to firing of an event getting blocked.
Try using:
Element fg = ie.TextField(Find.ByName("password"));
fg.DomContainer.RunScript("$('#"+fg.id+'").change();");
This solved a similar problem for me.
Ok. Then try to use Eval function which takes java script code. Pass the two elements to the below method and check.
private void ChangeAndBlur(Element element)
{
try
{
element.DomContainer.Eval(string.Format("$('#{0}').change()", element.Id));
element.DomContainer.Eval(string.Format("$('#{0}').blur()", element.Id));
}
catch
{ }
}

Categories

Resources