I'm using setCustomValidity function to check if the new password and the repeat password are equals but , I debugged the code and the comparisson its correct but the error message its not shown and the form post request its done
<form action="/register" method="post" onsubmit="check_new_password()">
<div class="form-group">
and the javascript
function check_new_password(){
var new_pass = $('#new-password').val();
var repeated_pass = $('#repeat-password').val();
if(new_pass != repeated_pass){
$('#repeat-password')[0].setCustomValidity('Password are not equals');
}else{
$('#repeat-password')[0].setCustomValidity('');
}
You need to add the return statement in the onsubmit attribute, like this:
onsubmit="return check_new_password();"
So, the check_new_password() function needs to return a boolean according the validation.
Don't forget call the .reportValidity(); method because you're using HTMLObjectElement.setCustomValidity() method.
Additionally, you should add oninput="setCustomValidity('');" on the inputs fields to force to update its state.
See in this example:
function check_new_password() {
var new_pass = $('#new-password').val();
var repeated_pass = $('#repeat-password').val();
if (new_pass != repeated_pass) {
$('#repeat-password')[0].setCustomValidity('Password are not equals.');
$('#repeat-password')[0].reportValidity();
return false;
} else {
$('#repeat-password')[0].setCustomValidity('');
return true;
}
}
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
<form action="/register" method="post" onsubmit="return check_new_password();">
<div class="form-group">
<label for="new-password">Password:</label>
<input id="new-password" class="form-control" type="password" oninput="setCustomValidity('');" />
</div>
<div class="form-group">
<label for="repeat-password">Repeat Password:</label>
<input id="repeat-password" class="form-control" type="password" oninput="setCustomValidity('');" />
</div>
<div>
<button class="btn btn-xs btn-primary" type="submit">Send</button>
</div>
</form>
</div>
Related
Trying to validate a form but I am facing constant problems. Here is the code
HTML:
<form id="regForm" class="form-group" method="POST" action="signup.php">
<div class="col-md-12">
<h2>Job Pocket</h2>
</div>
<div class="col-md-12">
<input placeholder="email" class="form-control"type="text" name="email" id="email">
</div>
<div class="col-md-12">
<input placeholder="password" class="form-control" type="password" name="password" id="password">
</div>
<div class="col-md-12">
<input placeholder="confirm password" class="form-control" type="password" name="confirmpass" id="confirmpass">
</div>
<div class="container">
<div class="row">
<div class="col-md-6">
<input placeholder="first name" class="form-control" type="text" name="first_name" id="first_name">
</div>
<div class="col-md-6">
<input placeholder="last name" class="form-control" type="text" name="last_name" id="last_name">
</div>
</div>
</div>
<div class="col-md-12">
<input type="submit" onclick="return validation()"class="btn btn-primary"name="submitsignup" id="submitsignup" value="submit">
</div>
<hr>
</form>
</div>
</div>
</div>
</div>
</div>
</main>
<p id="mg"></p>
</div>
JavaScript:
<script type="text/javascript">
function validation(){
if(document.getElementById("email").value=="" || document.getElementById("password").value=="" || document.getElementById("last_name").value=="" || document.getElementById("first_name").value==""){
document.getElementById("mg").innerHTML="Fill all fields";
return false;
}
var emails = document.getElementById("email").value;
else if(emails.indexOf('#') <= 0){
document.getElementById('mg').innerHTML =" ** # Invalid Position";
return false;
}
else if((emails.charAt(emails.length-4)!='.') && (emails.charAt(emails.length-3)!='.')){
document.getElementById('mg').innerHTML =" ** . Invalid Position";
return false;
}
else {
document.getElementById("regForm").submit();
}
}
</script>
The form keeps submitting itself. It works for the first if statement but after that it ignores the two else if and submits itself.
Even if I comment out this statement, it still submits to signup.php
document.getElementById("regForm").submit();
At the moment I have no idea why it is submitting so I am adding the php code aswell.
if(isset($_POST['submitsignup'])){
$date = array();
if($_POST['email']=='' || $_POST['password']=='' || $_POST['first_name']=='' || $_POST['last_name']==''){
$template->error="Please fill all fields";
}}
I added this bit of code in the signup.php file for an extra check but I have seen that it strightup submits to signup.php.
EDIT: Updated answer to updated question
Your problem might be related to the fact that you have this line of code:
var emails = document.getElementById("email").value;
before the elseif, which might break the if elseif flow.
Try using this code instead:
function validation(){
var emails = document.getElementById("email").value;
if(emails=="" || document.getElementById("password").value=="" || document.getElementById("last_name").value=="" || document.getElementById("first_name").value==""){
document.getElementById("mg").innerHTML="Fill all fields";
return false;
}
else if(emails.indexOf('#') <= 0){
document.getElementById('mg').innerHTML =" ** # Invalid Position";
return false;
}
else if((emails.charAt(emails.length-4)!='.') && (emails.charAt(emails.length-3)!='.')){
document.getElementById('mg').innerHTML =" ** . Invalid Position";
return false;
}
else {
document.getElementById("regForm").submit();
}
}
Try with:
<input type="button"
instead:
type="submit"
Edit: otherwise your .submit() function is useless.
-2 ? Tell me why using .submit() if the form as already submit type ?
Good morning,
I'm working on some simple form validation. Whenever I submit my form, the error message appears, but I can repeatedly spam the button for numerous error messages. Is there a way I can change this to only show the error message once? I've also noticed that even if I populate both fields it will still flash quickly in my console with the error log but not show the error.
Can anyone tell me what I'm doing wrong here?
var uname = document.forms['signIn']['userame'].value;
var pword = document.forms['signIn']['password'].value;
function validateMe (e) {
if (uname.length || pword.length < 1 || '') {
var container = document.getElementById('error-container');
var errorMsg = document.createElement('div');
errorMsg.className = 'error-message';
errorMsg.innerHTML = '<span class="heading-large">Please enter a valid username or password</span>';
container.appendChild(errorMsg);
console.log('An error occured');
return false;
}
}
<form id="signIn" action='#'>
<div class="boxed left-floater">
<h1 class="heading-large margin-top">Sign in</h1>
<div id="error-container"></div>
<div class="form-group">
<label class="form-label-bold" for="username">Username</label>
<input class="form-control log-in-form-control" id="username" name="username" type="text">
</div>
<div class="form-group">
<label class="form-label-bold" for="password">Password</label>
<input class="form-control log-in-form-control" id="password" type="password" name="password">
</div>
<div>
<a class="right-floater forgotten-password" href="forgottenpassword.html">Forgotten Password</a>
<button class="button clear right-floater" type="submit" onclick="validateMe();">Sign In</button>
</div>
</div>
</form>
Fiddle
You must be clearing the contents of your container to avoid duplication of elements. Below are few things to note:
You were trying to get userame instead of username in your fiddle. May be spelling mistake.
Keep input type=submit instead of button
Pass the event to your validateMe function to prevent the default action of post.
Move the variables within the function to get the actual value all the time
function validateMe(e) {
e.preventDefault();
var uname = document.forms['signIn']['username'].value;
var pword = document.forms['signIn']['password'].value;
var container = document.getElementById('error-container');
container.innerHTML = ''; //Clear the contents instead of repeating it
if (uname.length < 1 || pword.length < 1) {
var errorMsg = document.createElement('div');
errorMsg.className = 'error-message';
errorMsg.innerHTML = '<span class="heading-large">Please enter a valid username or password</span>';
container.appendChild(errorMsg);
console.log('An error occured');
return false;
}
}
<form id="signIn" action='#'>
<div class="boxed left-floater">
<h1 class="heading-large margin-top">Sign in</h1>
<div id="error-container"></div>
<div class="form-group">
<label class="form-label-bold" for="username">Username</label>
<input class="form-control log-in-form-control" id="username" name="username" type="text">
</div>
<div class="form-group">
<label class="form-label-bold" for="password">Password</label>
<input class="form-control log-in-form-control" id="password" type="password" name="password">
</div>
<div>
<a class="right-floater forgotten-password" href="forgottenpassword.html">Forgotten Password</a>
<input value="Sign In" class="button clear right-floater" type="submit" onclick="validateMe(event);" />
</div>
</div>
</form>
Updated Fiddle
Edit - if condition was failing and have updated it accordingly
this is full work code
var uname = "";
var pword = "";
function validateMe(e) {
e.preventDefault();
uname = document.forms['signIn']['username'].value;
pword = document.forms['signIn']['password'].value;
if (uname.length || pword.length < 1 || '') {
var container = document.getElementById('error-container');
var errorMsg = document.createElement('div');
errorMsg.className = 'error-message';
errorMsg.innerHTML = '<span class="heading-large">Please enter a valid username or password</span>';
container.appendChild(errorMsg);
console.log('An error occured');
return false;
}
return true;
}
<form id="signIn">
<div class="boxed left-floater">
<h1 class="heading-large margin-top">Sign in</h1>
<div id="error-container"></div>
<div class="form-group">
<label class="form-label-bold" for="username">Username</label>
<input class="form-control log-in-form-control" id="username" name="username" type="text">
</div>
<div class="form-group">
<label class="form-label-bold" for="password">Password</label>
<input class="form-control log-in-form-control" id="password" type="password" name="password">
</div>
<div>
<a class="right-floater forgotten-password" href="forgottenpassword.html">Forgotten Password</a>
<button class="button clear right-floater" type="submit" onclick="validateMe(event);">Sign In</button>
</div>
</div>
</form>
I am trying to print the value from the form when a user submits the function but a blank value is returned.
Here is my JavaScript code:
var login = new function()
{
var name = null ;
this.validation = function()
{
this.name = document.getElementById("Username").value;
console.log(this.name);
document.getElementById("demo").innerHTML = this.name;
};
};
And my HTML form as :
<body>
<div class="container">
<div class="col-md-8">
<div class="starter-template">
<h1>Login with javascript</h1>
<p class="lead">Please Enter Following Details</p>
<h1 id="demo"></h1>
<form name="form" onSubmit="return login.validation();" action="#" method="post">
<div class="form-group">
<label for="exampleInputEmail1">Username</label>
<input type="text" name="username" class="form-control" id="Username" placeholder="Please Enter your Username">
</div>
<div class="form-group">
<label for="exampleInputEmail1">Email address</label>
<input type="email" class="form-control" id="Email" placeholder="Please enter your Password">
</div>
<div class="form-group">
<label for="exampleInputPassword1">Password</label>
<input type="password" class="form-control" id="Password" placeholder="Password">
</div>
<div class="form-group">
<label for="exampleInputPassword1">Re-Password</label>
<input type="password" class="form-control" id="Re-Password" placeholder="Password">
</div>
<button type="submit" class="btn btn-default">Submit</button>
</form>
</div>
</div>
</div>
<script src="js/login.js"></script>
<script href="js/bootstrap.js"></script>
<!-- /.container -->
</body>
Why does the value not get into html <p> tag.
Your code simply works. But since the function executes on submitting the form, the username gets logged in the console fast before the page refreshed with submitted data. You can confirm this and test it by adding event.preventDefault(); to the function to prevent submitting the form so the page would stay visible with the console.
<script>
var login = new function()
{
var name = null ;
this.validation = function()
{
event.preventDefault();
this.name = document.getElementById("Username").value;
console.log(this.name);
document.getElementById("demo").innerHTML = this.name;
};
};
</script>
If that's not what you're looking for, let me know.
We the javascript validation failed you need to return false. If you don't it will proceed your form further. Thanks
var login = new function()
{
var name = null ;
this.validation = function()
{
this.name = document.getElementById("Username").value;
document.getElementById("demo").innerHTML = this.name;
return false;
};
};
I am not able to see error message on clicking the submit button using angularjs.
Any lead will be appreciated
Thanks in advance :)
<form id="formbody" ng-submit="submituser(form)" name="form" novalidate>
<input type="text" ng-class="{ errorinput: submitted && form.dob.$invalid }" name="dob" ng-model="dob" placeholder="Date of Birth" required />
<span class="e" ng-show="submitted && form.dob.$invalid">Please provide a valid date of birth</span>
<div style="padding-left: 275px;">
<button type="submit">Submit</button>
<!-- <div type="button" id="btn" style="color: red;" >Submit</div> -->
</div>
</div>
</form>
.controller('ExampleController', function($scope, $location, $scope, $stateParams) {
$scope.singleSelect = '';
$scope.goToPage = function() {
console.log("selectservice");
$location.path("/selectservice");
}
$scope.submituser = function($scope) {
if ($scope.form.$valid) {} else {
$scope.submitted = true;
}
}
})
change ng-show of span to
<span class="e" ng-show="submitted && form.dob.$invalid">Please provide a valid date of birth</span>
please check the form name
you have used two different names
name ="form" in form tag and used as signUpForm.dob in input field.
Check your ng-model to
<form id="formbody" ng-submit="submituser(form)" name="signUpForm" novalidate>
<input type="text" ng-class="{ errorinput: submitted && signUpForm.dob.$invalid }" name="dob" ng-model="form.dob" placeholder="Date of Birth" required />
<span class="e" ng-if="submitted && signUpForm.dob.$invalid">Please provide a valid date of birth</span>
<div style="padding-left: 275px;">
<button type="submit">Submit</button>
</div>
</div>
</form>
.controller('ExampleController',function($scope,$location,$scope, $stateParams){
$scope.singleSelect='';
$scope.goToPage=function(){
console.log("selectservice");
$location.path("/selectservice");
}
$scope.submitted =false;
$scope.submituser = function(form){
// console.log(form);
if (form.$valid) {
your logic
} else {
$scope.submitted = true;
}
}
})
Try something like that
<link href="http://netdna.bootstrapcdn.com/twitter-bootstrap/2.3.1/css/bootstrap-combined.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form name="form" ng-app>
<div class="control-group" ng-class="{true: 'error'}[submitted && form.dob.$invalid]">
<label class="control-label" for="dob">Your Date of Birth</label>
<div class="controls">
<input type="text" name="dob" ng-model="dob" required />
<span class="help-inline" ng-show="submitted && form.dob.$invalid">Please provide a valid date of birth</span>
</div>
</div>
<button type="submit" class="btn btn-primary btn-large" ng-click="submitted=true">Submit</button>
</form>
You have to provide the form name but even after that you cannot refer to your form in controller unless you pass it through the submit function arguments. Also there is not signupForm() function in your controller.
The way to go is :
<form id="formbody" name="myForm" ng-submit="signupForm(myForm)" novalidate>
<!-- inputs etc -->
</form>
Then based on submituser():
$scope.signupForm = function(myForm) {
//Do whatever you want to do
if(myForm.$valid) {
//some logic
}else {
$scope.submitted = true;
}
}
On the other hand if you don't want to mess up with the controller you can always use FormController method $submitted. This would look like:
<span class="e" ng-show="myForm.$submitted && myForm.dob.$invalid">Please provide a valid date of birth</span>
I have a HTML Form and on submit, a validate() function to be called.
The submit works fine, if the validate() function is within the "script" tag at the end of the "body" tag.
Otherwise, the submit doesn't call the validate() function when it is present in external js file, even though document.ready is used, as in https://jsfiddle.net/vg47127o/1/
HTML --
<form method="post" action="#" onsubmit="return validate()" name="loginForm" class="form-horizontal" role="form">
<div class="form-group">
<p class="error-block"><span class="glyphicon glyphicon-exclamation-sign"> </span> <span class="error-msg"></span></p>
</div>
<div class="form-group">
<label class="control-label col-sm-3" for="username">username:
</label>
<div class="col-sm-9">
<input type="text" class="form-control digits-only" id="username" placeholder="Enter Username">
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-3" for="password">Password:</label>
<div class="col-sm-9">
<input type="password" class="form-control" id="password" placeholder="Enter Password">
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-4 col-sm-8">
<button type="submit" id="loginBtn" class="btn btn-default">Log In</button>
<button type="reset" class="btn btn-default">Reset</button>
</div>
</div>
</form>
SCRIPT --
$(document).ready(function() {
var displayError = function(error, msg) {
$(".error-block .error-msg").text(msg);
if (error === true)
$(".error-block").show();
else
$(".error-block").hide();
return true;
};
//Validating the input fields
var validate = function() {
var $username = $("#username").val(),
$password = $("#password").val();
if ($username === '' || $password === '') {
displayError(true, ' Username or Password cannot be empty. ');
return false;
} else if ($username.length < 6 || $password.length < 6) {
displayError(true, ' Username and Password should be a minimum of 6 characters. ');
return false;
} else {
displayError(false, ' ');
return true;
}
};
});
Am I missing out something here or What could be the reason for this.
Here's an updated fiddle that is working. You need to trap the submit() event if validate does not return true.
This is what you would include in your jQuery:
$("form").on("submit", function (event) {
if (!validate()) {
event.preventDefault();
}
});
Then your <form> tag would simply be <form method="post" action="#" name="loginForm" class="form-horizontal" role="form">
FYI
The reason for this is that when your validate() function is inside of your document ready, it is scoped to the document ready function, therefore, inline DOM event triggers do not have access to it. You have to set up the event handler inside the jQuery function, or declare your validate() function outside of your document ready function.
The validate variable is scoped to the anonymous function you put into $(document).ready. That means it can be accessed only from within that function and not from the page which lives in the global scope.
Add the event listener using the $(...).submit function instead:
$(document).ready(function() {
/* *** */
//Validating the input fields
$("[name=loginForm]").submit(function() {
var $username = $("#username").val(),
$password = $("#password").val();
/* *** */
});
});