I have created a form. I have two email fields one is for Email and the other is confirm Email.
I wanted to create a directive which will compare confirmEmail field and Email field on blur of ConfirmEmail field. And on blur of confirm email i wanted to validate and show message if it doesn't match with email field.
Doubt: I am almost done. But somehow the onblur is not behaving properly.
One of the below case:
When I enter a#x in email field. Then a#t in confirm email field and tab out. I see the validation message as it doesn't match.
After that when I go back to confirm email field and make a#xsdf and tab out the validation doesn't fire.But if I type in some other textbox in the form like firstname then message gets reflected. Could you please suggest what is wrong in the code.
<!DOCTYPE html>
<html ng-app="myapp">
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0-beta1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.0/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.0/angular-route.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0-alpha/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0-alpha/css/bootstrap.min.css">
<script src="script.js"></script>
<link rel="stylesheet" type="text/css" href="style.css">
<title></title>
</head>
<form name="myForm" novalidate>
<div class="col-xs-12" ng-controller="myController">
<br>
<br> First Name
<br>
<firstname></firstname>
<div ng-if="myForm.txtFirstName.$dirty">
<div class="danger" ng-show="myForm.txtFirstName.$error.pattern">
Enter First Name without Special Character
</div>
</div>
<br>
<br> Last Name
<br>
<input type="text" ng-model="LastName" name="txtLastName" class="form-control"></input>
<br>
<br> Email
<br>
<input type="email" name="txtemail" ng-model="Email" class="form-control"></input>
<div ng-if="myForm.txtemail.$dirty">
<div class="danger" ng-show="myForm.txtemail.$invalid">
Enter Valid Email Id
</div>
</div>
<br>
<br> Confirm Email
<br>
<input type="text" name="txtConfirmEmail" ng-disabled="!myForm.txtemail.$viewValue"
ng-model="EmailConfirm" match match-Email="{{Email}}" match-Cemail="{{EmailConfirm}}" class="form-control"></input>
<div class="danger" ng-show="mismatch">
<span>Email and Confirm Email must match.</span>
</div>
</div>
</form>
</html>
https://plnkr.co/edit/Tn70GxyqAadg0EdqjFG6?p=preview
jquery events doesnt trigger $digest circle of angular, you should use $apply for trigger this circle
scope.mismatch = false;
debugger
if (attrs.matchEmail === attrs.matchCemail) {
scope.$apply(function(){
scope.mismatch = false
});
} else
scope.$apply(function(){
scope.mismatch = true
});
});
One way around is to replace {{Email}} with current form value:
<input type="text" name="txtConfirmEmail" ng-disabled="!myForm.txtemail.$viewValue"
ng-model="EmailConfirm" match match-Email="{{myForm.txtemail.$viewValue}}" match-Cemail="{{EmailConfirm}}" class="form-control" />
You should get into the habit of using the "dot" on the scope; In your situation you should be using:
$scope.model = {
mismatch: false
}
Here's your fixed plunker: https://plnkr.co/edit/XEZjkXaIecGC4oBox5Z0?p=preview
Related
I have added Google reCaptcha v3 script to my form. The form also includes validation that alerts the user to complete the input field. Now when the user clicks on submit button directly, an alert is shown and when OK is clicked the page refreshes and form data is submitted in the backend. I have tried adding return false and e.preventdefault() in the function but the page still resets after the alert. If I try to add any additional condition to the data-callback function, the submit button stops working.
HTML
<html>
<head>
<script src="https://www.google.com/recaptcha/api.js"></script>
<script>
function onSubmit(token) {
document.getElementById("demo-form").submit();
}
</script>
<script>
function validateForm() {
var fname = document.forms.WebForm.fname.value;
if (fname == "") {
alert("Please fill out all the fields");
return false;
}
}
</script>
</head>
<body>
</style>
<div class="container">
<form action="https://www.samepage.com" method="post" id="demo-form" name="WebForm">
<div>
<div>
<input name="fname" id="fname" type="text" placeholder="First name*" required/>
</div>
</div>
<div>
<div>
<input type = "submit" style = "font-weight: bold;" value="Submit" class="g-recaptcha button" data-sitekey="xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
data-callback='onSubmit'
data-action='submit'
onClick="return validateForm()"/>
</div>
</div>
</form>
</div>
</body>
</html>
Even the required attribute in the input tag doesn't work with the recaptcha script added. When I remove the data-callback attribute and the supporting script functions, the alert and form works as expected.
First, Happy New Year everyone!
I tried make a Form in which the Check Boxes(text)at the start(calling a function, verif()) where they must be in different color than as soon the user input a name the Colors must change in white, also I use the method, setCustomValidity to advice the user to fill the box in a case he(she) forgot but even I don't get the error massage where I must fill the box.
Unfortunately my plan looks has error but I don't know where is that.
<section id="secty">
<h1 id="demo">Managing Form</h1>
<form id="usuer_register" name="usuer_register" method="post">
<table>
<tr><td>Name:</td>
<td><input type="text" id="nam" name="nam"></td></tr>
<tr><td>Last name:</td>
<td><input type="text" id="name1" name="name1"></td></tr>
<tr><td>Age:</td>
<td><input type="text" id="age" name="age"></td></tr>
<tr><td><input type="submit" id="regist" name="regist"></td></tr>
</table>
</form>
</section>
<script>
function start(){
var x=document.getElementById("nam");
var y=document.getElementById("name1");
x.addEventListener("input", verif, false);
y.addEventListener("input", verif, false);
verif();
}
function verif(){
if(x.value=="" && y.value==""){
x.setCustomValidity("Enter Name or Lastname");
x.style.background="#803ADD";
y.style.background="#803ADD";
}
else{
x.setCustomValidity(""); // this restart as default;
x.style.background="#FFFFFF";
y.style.background="#FFFFFF";
}
}
window.addEventListener("load", start, false);
</script>
There's a bunch here to re-work. Check the HTML, CSS, and JavaScript comments in the code below for details, but the main point is that HTML, CSS, and JavaScript already provide most of the functionality you are looking for. If you simply add required to the input elements that cannot be blank, you'll get automatic validity checking and styling.
Check our how HTML5 Form Validity works.
<!DOCTYPE html>
<html>
<head>
<title>Form Validation</title>
<style>
/* CSS provides valid and invalid pseudo-classes which will automatically
kick in based on the validity of form elements */
.validate:valid { background-color:#fff; }
.validate:invalid { background-color:#803ADD; }
label { display:inline-block; width: 5em; }
form > div { margin-bottom: .2em; }
</style>
</head>
<body>
<section>
<h1>Managing Form</h1>
<!-- Don't forget to fill in the action attribute of the form! -->
<form id="usuer_register" name="usuer_register" method="post" action="">
<!-- Do not use tables for layout! They are only for displaying tabular data. -->
<div>
<!-- Use label elements with form fields for better accessibility.
Now, clicking on the label text focuses the field. Also, type="text"
is not required on textboxes as "text" is the default type.
Lastly, just add the "required" attribute for automatic validity checking. -->
<label for="fName">Name: </label><input id="fName" name="fName" class="validate" required>
</div>
<div>
<label for="lName">Last Name: </label><input id="lName" name="lName" class="validate" required>
</div>
<div>
<label for="age">Age: </label><input id="age" name="age">
</div>
<div>
<!-- Submit Buttons shouldn't have a name because they
don't have any data that you would want submitted
along with the form. -->
<input type="submit">
</div>
</form>
</section>
<!-- As long as your script element is the last element
in the body, there is no need for a "start" function
or a "load" event hander. The following code will just
run when it is reached and at this point in the document
all the HTML has been parsed. -->
<script>
// Use meaningfull variable names
let fName = document.getElementById("fName");
let lName = document.getElementById("lName")
// The inputs will be invalid initially, so flag them
// that way from the start
fName.setCustomValidity("Enter First Name");
lName.setCustomValidity("Enter Last Name");
fName.addEventListener("input", verif);
lName.addEventListener("input", verif);
function verif(){
// The field has recieved input, so the required validation
// requirement has been met.
this.setCustomValidity("");
}
</script>
</body>
</html>
Happy New Year!
When I use default HTML validation it shows the default error messages which is not I want to show to my clients. I need to customize the message and give different massages for each validations such as min, max, type and require. For Example:
The field is required, The value does not match
Refer the tradition HTML Code:
<input type="text" required>
I want something like this:
<input type="text" validation="required|my_message,min:5|my_message">
It's totally possible with custom libraries in jQuery which I would suggest - https://github.com/aslamanver/abvalidate
Custom Message - jQuery Form Validation - abValidate.js
ab-validation="required|Hey dude you missed that,min:5| No no you want to type more" name="name"
Use this library by adding these CDNs
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!-- abValidate Library -->
<script type="text/javascript" src="https://raw.githubusercontent.com/aslamanver/abvalidate/master/abValidate.min.js">
<link rel="stylesheet" href="https://raw.githubusercontent.com/aslamanver/abvalidate/master/abValidate.css">
Initialize the library
$(document).ready(function () {
//.ab-form is your form class
$(".ab-form").abValidate();
});
There you go, now you can use your custom validation using jQuery abValidate library
<form class="ab-form" action="your_action_url">
<!-- Input and error message should be in a div class -->
<div class="my-form-group">
<input type="text" ab-validation="required|Hey dude you missed that,min:5| No no you want to type more" name="name" class="ab-validation-i" />
<div class="error"></div>
</div><br>
<div class="my-form-group">
<input type="submit" name="submit" value="Submit">
</div>
</form>
Try this one, its better and tested:
HTML:
<form id="myform">
<input id="email"
oninvalid="InvalidMsg(this);"
oninput="InvalidMsg(this);"
name="email"
type="email"
required="required" />
<input type="submit" />
JAVASCRIPT:
function InvalidMsg(textbox) {
if (textbox.value === '') {
textbox.setCustomValidity('Required email address');
} else if (textbox.validity.typeMismatch){
textbox.setCustomValidity('please enter a valid email address');
} else {
textbox.setCustomValidity('');
}
return true;
}
Demo:
http://jsfiddle.net/patelriki13/Sqq8e/
i'm with a ridiculous problem (i think). I just can't get a tag content using a Script/Function/document.getElementById. The alert tha i'm using to see the content of variable (wM) is always blank. I looked a lot of examples in the Web and all of them is similar, sometimes just like my code. See below:
<!DOCTYPE html>
<html lang ="pt-br">
<head>
<title> loginServlet2 </title>
<meta http-equiv = ”Content-Type” content=”text/html; charset=UTF-8”>
<link rel="stylesheet" type="text/css" href="c:/java/html/css/estilo.css"/>
<script type="text/javascript">
function oMsg()
{
var wM = document.getElementById("wMsgB").textContent;
// var wM = document.querySelector("span").textContent;
alert("wM = "+ wM);
if (wM == "Teste OK!")
{
// document.getElementById("wMsgA").innerHTML = "Test is OK";
document.getElementById("wMsgA").textContent = "Test is OK";
}
else
{
alert("Test is not OK. Before set new msg");
document.getElementById("wMsgA").textContent = "Test is not OK";
}
}
</script>
</head>
<body>
<h2> Login Page2 </h2>
<p>Please enter your username and password</p>
<form method="GET" action="loginServlet2">
<p id="test2"> Username <input type="text" name="userName" size="50"> </p>
<p> Password <input type="password" name="password" size="20"> </p>
<p> <input type="submit" value="Submit" name="B1" onclick="oMsg()"> </p>
</form>
<h3> MsgB : <span id="wMsgB"<%=request.getAttribute("wMsg")%></span></h3>
<p> MsgA : <span id="wMsgA"> </span> </p>
</body>
</html>
Could anyone help me, please? Thanks.
You are trying to get the value of a p element, but p elements don't have a value property. Only form fields do. Non-form fields that contain text between their opening and closing tags have .textContent and .innerHTML properties you can use to get/set their contents.
If you want to give the user a place to type in some data, you need to create some input form fields and then you have to wait until they've done that before attempting to get the values.
Next, you have smart quotes “” instead of straight quotes "" which can cause encoding problems. Make sure you write your code in an editor that doesn't apply any formatting to the code. There are plenty of great free web editors out there.
You also have a reference to a .css file using a full local path, which isn't going to work when you deploy this code later. You should be using relative paths to reference files that are part of your system.
Finally, you are using some old HTML syntax in your meta, link and script tags, so take note of the modern versions of those in the snippet below.
<head>
<title>loginServlet2</title>
<meta charset=UTF-8”>
<link rel="stylesheet" href="c:/java/html/css/estilo.css"/>
<script>
function oMsg() {
var wM = document.getElementById("wMsg").textContent;
alert("wM = " + wM);
if (wM == "Test OK!") {
document.getElementById("wMsgA").textContent = "Test is OK";
} else {
alert("Test is not OK. Before set new msg");
document.getElementById("wMsgA").textContent = "Test is not OK";
}
}
</script>
</head>
<body>
<h2> Login Page2 </h2>
<p>Please enter your username and password</p>
<form method="GET" action="loginServlet2">
<p id="test2"> Username <input type="text" name="userName" size="50"> </p>
<p> Password <input type="password" name="password" size="20"> </p>
<p> <input type="submit" value="Submit" name="B1" onclick="oMsg()"> </p>
</form>
<h2>MsgB : <span id="wMsg"><%=request.getAttribute("wMsg")%></span> </h2>
<p>MsgA : <span id="wMsgA"> </span> </p>
I don't know why I received this error when I changed the code to php (from html). when the extension of the file is html, the code is working fine.
<?php?>
<html lang="en">
<head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<link rel="stylesheet" href="css/manual.css">
<!-- Optional theme -->
<!-- Latest compiled and minified JavaScript -->
<script src="http://code.jquery.com/jquery-latest.min.js"
type="text/javascript"></script>
<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.14.0/jquery.validate.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.14.0/jquery.validate.min.js"></script>
<title>Register</title>
</head>
<body>
<nav class="navbar navbar-default" id="navBar">
</nav>
<div class="full">
<div class="col-xs-12">
<!--Side Bar-->
<div class="col-xs-3" id="navSide">
</div>
<div class="col-xs-6" id="signUpForm">
<h1>Register Page</h1>
<form role="form" id="signUpForm">
<div class="form-group">
<div class="form-inline spacer-12">
<input type="text" class="form-control" name="userFirstname" placeholder="First Name">
<input type="text" class="form-control" name="userLastName" placeholder="Last Name">
</div>
</div>
<div class="form-group ">
<input type="text" class="form-control"
name="userEmail"
placeholder="Email">
</div>
<div class="form-group ">
<input type="password" class="form-control" name="userPassword" placeholder="Password">
</div>
<div class="form-group ">
<input type="password" class="form-control" name="confirmPassword" placeholder="Password">
</div>
<div class="form-group ">
<label> Birthday* </label>
<input type="date" class="form-control" name="userBirthday" placeholder="Birthday">
</div>
<input type="submit" class="btn btn-info spacer-12" style="clear:both" >
</form>
</div>
</div>
</div>
<script src="js/startup.js"></script>
<script src="js/signup.js"></script>
</body>
</html>
<?php?>
then this is my jquery validation code
$(document).ready(function(){
$('#signUpForm').validate({
errorElement: "span",
errorClass: "help-block",
rules:{
userFirstName:{
required: true
},
userLastName:{
required: true
},
userEmail:{
required: true
},
userPassword:{
required: true
},
confirmPassword:{
required: true
},
userBirthday:{
required: true
}
},
submitHandler: function (form) { // for demo
alert('valid form submitted'); // for demo
return false; // for demo
},
highlight: function(element) {
$(element).closest('.form-group').addClass('has-error').addClass('red-border');
},
unhighlight: function(element) {
$(element).closest('.form-group').removeClass('has-error').addClass('has-success').removeClass('red-border');
}
});
});
This code causes error when I click the submit button (JQuery Validate Uncaught TypeError: Cannot read property 'settings' of undefined )
But the error is temporary and will vanish in a while.
You defined two ids with same name, whereas id should be unique.
<div class="col-xs-6" id="signUpForm">
<form role="form" id="signUpForm">
Try to remove id from <div class="col-xs-6" id="signUpForm">
If you use the rules() method, make sure to initialize the validation first.
var validator = $("#Form1").validate();
$('#field1').rules("add", {
min: 1
});
This error is normally caused by trying to validate an element that is not a form. In the OP's case, there are two elements with the same ID:
<div class="col-xs-6" id="signUpForm">
<form role="form" id="signUpForm">
jQuery searches a page from top to bottom, and the first element it finds with this ID is not a form.
The Validator.element() function (for validating single elements) can also cause this error, if attempting to validate an element that is outside the form.
NOTE two things
1. Define the Jquery function
include the function of jQuery !
(function( $ ) {
//Start Script
//endscript/
})( jQuery );
Change the Form Id because it's doing conflict between Form Id and Div Id
<form role="form" id="signUpForm1"> // include 1 in previous form id
And put this id into script
$('#signUpForm1').validate({ // put the Id in the script
Hope Your Task will be successful.
To add a small detail here, I ran into the same problem with jQuery UI time picker, and it also was due to the id being non-unique.
In my case, it's because I was grabbing the parent element from a template - duplicating it for a pop-up window. As a result, the contents of the window all had duplicate ids.
My normal workaround for that was to replace this:
$('#foo').bar();
with this:
myPopupWindow.find('#foo').bar();
That works quite well for most things, but not for the time picker. For that one, I wound up doing this:
myPopupWindow.find('#foo').attr('id', 'foo_' + someUniqueTag);
myPopupWindow.find('#foo_' + someUniqueTag).timepicker();
where someUniqueTag is a record id, random number or some other distinct string. This solved it quite nicely for me.