I have the next input field:
<form action="admin" method="POST" commandName="adminForm" onsubmit="return validateEmail(this.email)">
<table>
<tr>
<td>
<label for="email">Email</label>
</td>
<td>
<input id="email" name="email" type="text" path="email" oninvalid="this.setCustomValidity('Please fill this field - it is mandatory')" oninput="setCustomValidity('')">
</td>
</tr>
</table>
</form>
function validateEmail(email) {
var re = /^([\w-]+(?:\.[\w-]+)*)#((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
if (!re.test(email.value)) {
email.setAttribute("oninvalid", "this.setCustomValidity('Wrong email format')");
email.setAttribute("oninput", "setCustomValidity('')");
return false;
}
return re.test(email.value);
}
Here I want to display error message when the wrong email is added. Now when I do not add something under the email field, it shows error Please fill this field - it is mandatory. I want to change this message if email is wrong.
It currently does not work, any ideas why?
Refer to my example source.
html
<form id="myForm" action="admin" method="POST">
<table>
<tr>
<td>
<label for="email">Email</label>
</td>
<td>
<input id="email" name="email" type="text">
</td>
</tr>
</table>
<div id="msg"></div>
<button type="submit">submit</button>
</form>
and javascript
var form = document.getElementById('myForm');
var msg = document.getElementById('msg');
form.addEventListener('submit', function( e ) {
var re = /^([\w-]+(?:\.[\w-]+)*)#((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
var email = document.getElementById('email').value;
if (!re.test(email)) {
console.log('invalid');
msg.innerText = 'invalid email';
e.preventDefault();
} else {
msg.innerText = '';
}
});
and live demo
Related
why do I have this problem? I'm trying to get an output to the user name in the site. but it keeps giving me this problem!
I ant it to write me that the user name is not correct when im starting with a number or it is blanked at all- it gives me nothing.
please help me I am sitting on this above an hour:((
Snippet
function validateForm() {
var res = true;
res = userNameVal() && res;
return res;
}
function userNameVal() {
var userName = document.getElementById("username").value;
var msgBox = document.getElementById("userNameCheck");
if (userName.length == 0) {
msgBox.innerHTML = "You must enter user name";
msgBox.style.color = "red"
return false;
}
if (!isLetter(userName[0])) {
msgBox.innerHTML = "User name must start with a letter ";
msgBox.style.color = "red";
return false;
}
msgBox.innerHTML = "";
return true;
}
<form id="form1" method="post" onsubmit="return validateForm()">
<table class="table3">
<tr>
<td>
<label for="username">User Name:</label>
</td>
<td>
<input type="text"
name="username"
id="username"
onchange="userNameVal()" />
</td>
<td>
<div id="userNameCheck"></div>
</td>
</tr>
<tr>
<td><input type="button"
value="submit"
onclick="return validateForm()"/>
<input type="reset" value="reset" />
</td>
<td></td>
<td></td>
</tr>
</table>
</form>
I have been looking at some examples of form validation, where an invalid input will stop the user before proceeding to the next page. The way I have seen this done many times is using the event.preventDefault() function, but it just doesn't seem to be working for me. I'm not sure if the javascript function is wrong, or maybe it is just not being read at all. When I send in an invalid input it goes through to the next page anyway.
Here is my HTML code:
Header:
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="3.css"/>
<script type="text/javascript" src="3.js"></script>
<title>Login</title>
Body:
<section>
<h2>Login</h2>
<div id="loginInfo">
<form id="loginForm" method="post" action="nextpage.php" enctype="multipart/form-data">
<table id="loginTable">
<tr>
<td>
<input type="text" class="loginInput" id="loginEmail" name="loginEmail" placeholder="Email">
</td>
</tr>
<tr>
<td><label id="emailError" class="errorMsg"></label></td>
</tr>
<tr>
<td>
<input type="password" class="loginInput" id="loginPassword" name="loginPassword" placeholder="Password">
</td>
</tr>
<tr>
<td><label id="passError" class="errorMsg"></label></td>
</tr>
<tr>
<td></br><input type="submit" name="submit" id="loginSubmit" value="Login"></td>
</tr>
</table>
</form>
</div>
</section>
and here is the referenced 3.js code:
document.getElementById("loginForm").addEventListener("submit", loginFunction, false);
function loginFunction(event)
{
var valid= true;
var elements= event.currentTarget;
var email= elements[0].value;
var pass= elements[1].value;
var regexEmail= /^\w+#[a-zA-Z_]+?\.[a-zA-Z]{2,3}$/;
var regexPass= /^(\S*)?\d+(\S*)?\W+$/;
var emailError= document.getElementById(emailError);
var passError= document.getElementById(passError);
if (email == null || email == ""){
emailError.innerHTML= "Email is empty";
valid= false;
}
else if (regexEmail.test(email) == false){
emailError.innerHTML= "Incorrect Email format";
valid= false;
}
if (pass == null || pass == ""){
passError.innerHTML= "Password is empty.";
valid = false;
}
else if (regexPass.test(pass) == false) {
passError.innerHTML= "Incorrect password format";
valid = false;
}
else if (pass.length < 8){
passError.innerHTML= "Password is too short, must be 8+ characters";
valid= false;
}
if (valid == false){
event.preventDefault();
}
}
Can anyone explain where i've made my error?
This should do the trick:
<section>
<h2>Login</h2>
<div id="loginInfo">
<form id="loginForm" method="post" action="nextpage.php" enctype="multipart/form-data">
<table id="loginTable">
<tr>
<td>
<input type="text" class="loginInput" id="loginEmail" name="loginEmail" placeholder="Email">
</td>
</tr>
<tr>
<td><label id="emailError" class="errorMsg"></label></td>
</tr>
<tr>
<td>
<input type="password" class="loginInput" id="loginPassword" name="loginPassword" placeholder="Password">
</td>
</tr>
<tr>
<td><label id="passError" class="errorMsg"></label></td>
</tr>
<tr>
<td></br><input type="button" name="submit" id="loginSubmit" value="Login"></td>
</tr>
</table>
</form>
</div>
</section>
And this:
document.getElementById('loginSubmit').addEventListener('click',loginFunction,false);
function loginFunction()
{
var valid=true;
var elements=event.currentTarget;
var email=elements[0].value;
var pass=elements[1].value;
var regexEmail=/^\w+#[a-zA-Z_]+?\.[a-zA-Z]{2,3}$/;
var regexPass=/^(\S*)?\d+(\S*)?\W+$/;
var emailError=document.getElementById(emailError);
var passError=document.getElementById(passError);
if(email==null||email=='')
{
emailError.innerHTML='Email is empty';
valid=false;
}
else if(regexEmail.test(email)==false)
{
emailError.innerHTML='Incorrect Email format';
valid=false;
}
if(pass==null||pass=='')
{
passError.innerHTML='Password is empty.';
valid=false;
}
else if(regexPass.test(pass)==false)
{
passError.innerHTML='Incorrect password format';
valid=false;
}
else if(pass.length<8)
{
passError.innerHTML='Password is too short, must be 8+ characters';
valid=false;
}
if(!valid)
{
return
}
document.getElementById('LoginForm').submit();
}
I am struggling to understand where there is a mistake.
After many tries, I tend to think that it's something about overalcheck()...
The append, clearelement and writeto are the additional mini functions and they are totally fine.
So, this script checks the form, and if everything is ok, opens a new page. However, if a field is empty or has a wrong type, it shows the relative error message (or a list of error messages).
I made a lot of variations, sometimes it opens without a completed form (like the code below), sometimes it shows the error message for 1 field only and then, and even if you complete all fields, it still doesnt open a new page.
I would appreciate your help.
<script>
function overallcheck ()
{
if(!checkname() || !checkemail() || !checkjob())
{
writeTo("problemArea","Error messages area");
if(!checkname())
writeTo("problemArea","Please insert a valid name");
if(!checkemail())
writeTo("problemArea","Please insert a valid email");
if(!checkjob())
writeTo("problemArea","Please insert your job");
return false;
}
return true;
}
function checkname()
{
clearElement("problemArea");
var fullname = document.forms['form'].fullname.value;
if (fullname.length == 0 || !isNaN(fullname))
return false;
}
function checkemail()
{
clearElement("problemArea");
var mail = document.forms['form'].Email.value;
if (mail == '' || mail.indexOf('#') == -1 || mail.indexOf('.') == -1)
return false;
}
function checkjob()
{
clearElement("problemArea");
var i;
for (i=0;i<4;i++)
{
if (document.forms['form'].job[i].checked) {return true;}
}
return false;
}
</script>
<body>
<form onsubmit="return overallcheck();" action="res.html" id=form target="_blank" method="GET">
<table>
<tr>
<td><b><p>blabla?</p></b> </td>
<td> <input type="text" name="fullname" size="20" placeholder="Enter a valid name"/> </td>
</tr>
<tr>
<td><b><p> E-mail: </p></b></td>
<td><input type="email" name="email" maxlength="15" size = "20" placeholder="Enter a valid email address"/> </td>
</tr>
<tr>
<p><td><b><p>bla?</td></p>
<td>1<input type="radio" name="job" value="gov" /><br/>
2<input type="radio" name="job" value="pri" /><br/><div id="problemArea"> </div>
3<input type="radio" name="job" value="unem" /><br/>
4<input type="radio" name="job" value="other" /><br/>
</td></tr>
</table>
<p>
<button type="submit" onclick="" >clickme</button>
</form>
</body>
</html>
Track each error type with it's own div. Wrap overallcheck in a try catch to and alert errors. This helped find the "Email" error.
function writeTo(id, msg) {
document.getElementById(id).innerHTML += "<p>" + msg + "</p>";
}
function clearElement(id) {
document.getElementById(id).innerHTML = "";
}
function overallcheck() {
try {
if (!checkname() || !checkemail() || !checkjob()) {
if (!checkname())
writeTo("problem_fullname", "Please insert a valid name");
if (!checkemail())
writeTo("problem_email", "Please insert a valid email");
if (!checkjob())
writeTo("problem_blah", "Please insert your job");
return false;
}
return true;
} catch (err) {
alert(err);
}
}
function checkname() {
clearElement("problem_fullname");
var fullname = document.forms['form'].fullname.value;
if (fullname.length == 0 || !isNaN(fullname)) {
return false;
}
return true;
}
function checkemail() {
clearElement("problem_email");
var mail = document.forms['form'].email.value; //Email.value;
if (mail == '' || mail.indexOf('#') == -1 || mail.indexOf('.') == -1) {
return false;
}
return true;
}
function checkjob() {
clearElement("problem_blah");
var i;
for (i = 0; i < 4; i++) {
if (document.forms['form'].job[i].checked) {
return true;
}
}
return false;
}
td {
vertical-align: text-top;
}
.problem {
color: red;
}
<form onsubmit="return overallcheck();" action="res.html" id=form target="_blank" method="GET">
<table>
<tr>
<td><b><p>blabla?</p></b>
</td>
<td>
<input type="text" name="fullname" size="20" placeholder="Enter a valid name" />
<div id="problem_fullname" class="problem"></div>
</td>
</tr>
<tr>
<td><b><p> E-mail: </p></b>
</td>
<td>
<input type="email" name="email" maxlength="15" size="20" placeholder="Enter a valid email address" />
<div id="problem_email" class="problem"></div>
</td>
</tr>
<tr>
<p>
<td><b><p>bla?</td></p>
<td>
1<input type="radio" name="job" value="gov" /><br/>
2<input type="radio" name="job" value="pri" /><br/>
3<input type="radio" name="job" value="unem" /><br/>
4<input type="radio" name="job" value="other" /><br/>
<div id="problem_blah" class="problem"> </div>
</td></tr>
</table>
<p>
<button type="submit" onclick="" >clickme</button>
</form>
i have created one form with dynamically created fields. and i have a one check box with unique ID . when user clicks that check box then only those two fields are visible ("name and age"). after clicking only "age" field need to be validate .
here is my code :
$(document).ready(function() {
$('#person').click(function() {
function formValidator(){
var age = document.getElementsByName('age[]');
for (var i = 0; i< age.length; i++) {
if(!isNumeric(age[i], "Please enter a valid Age")){
return false;
}
}
return true;
}
function isNumeric(elem, helperMsg){
var numericExpression = /^[0-9]+$/;
if(elem.value.match(numericExpression)){
return true;
} else {
alert(helperMsg);
elem.focus();
return false;
}
}
});
});
$(document).ready(function() {
$('#person').click(function() {
$('#name').attr('required','required');
$('#age').attr('required','required');
});
});
style is :
.selectContainer{
display:none;
}
input[type=checkbox]:checked ~ .selectContainer {
display:block;
}
Html code is:
<form action="" method="post" onSubmit="return formValidator()">
<label for="name">Any Accompanying Person ?:</label>
<input type="checkbox" name="person" id="person" >Yes
<div class="selectContainer">
<br>
<label>Person Details</label>
<p>
<div style="padding-left:70px;">
<input type="button" value="Add Person" onClick="addRow('dataTable')" />
<input type="button" value="Remove Person" onClick="deleteRow('dataTable')" />
</div>
</p>
<table style="padding-left:50px;" id="dataTable" class="form" border="1" >
<tbody>
<tr>
<p>
<td><input type="checkbox" name="chk[]" checked="checked" /></td>
<td>
<label>Name</label>
<input type="text" size="20" name="name[]" id="name" >
</td>
<td>
<label>Age</label>
<input type="text" size="20" name="age[]" id="age" >
</td>
</p>
</tr>
</tbody>
</table>
<div class="clear"></div>
</fieldset>
</div>
</div>
<h3>Choose Your Payment Option</h3>
<h1>
<div style="padding-left:150px;">
<input type="radio" name="type" value="visa">VISA/MASTER CARD:<br />
<input type="radio" name="type" value="cheque"> CHEQUE/DEMAND DRAFT<br />
<input type="radio" name="type" value="neft">NEFT<br /><br/>
</div>
<label></label>
<input type="submit" name="submit" value="submit"><br />
</form>
problem: the form field "age" is validating successfully by clicking check box ("Any Accompanying Person ?:"). problem is when user try to submit the form without clicking that check box then all so its asking for validate . how get salutation for this ? please help
The validator is within a click handler, which should live outside of that (On the base on the document.ready()).
Also if you just want to validate when that checkbox is clicked you could check it within the javascript and select it via the name of the checkbox (If it has a unique ID each time).
function formValidator(){
var age = document.getElementsByName('age[]');
if($("input[name = 'chk[]']").prop('checked')){
for (var i = 0; i< age.length; i++) {
if(!isNumeric(age[i], "Please enter a valid Age")){
return false;
}
}
}
return true;
}
Bring all javascript functions outside of click events. Try this formValidator function
function formValidator(){
if($("#person").is(":checked")) {
var age = document.getElementsByName('age[]');
for (var i = 0; i< age.length; i++) {
if(!isNumeric(age[i], "Please enter a valid Age")){
return false;
}
}
}
return true;
}
I'm barely new to js but not on php-html web programming, but i confused to js usage.
I was using this js function to compare two input (password checking),
here's the fiddle
http://jsfiddle.net/EHUWC/1/
Nothing's wrong there, right?
but it won't work on my own webpage,
here's my code (im using codeigniter):
<div class="centerTitle">Sign Up Form</div>
<script>
function chkpassword() {
var p1 = document.getElementById("pass1").value;
var p2 = document.getElementById("pass2").value;
if (p1.length > 5) {
document.getElementById("passwordAlert").style.display = 'none';
if (p1 === p2) {
document.getElementById("passwordAlert").style.display = 'none';
validpass = "yes";
} else {
validpass = "no";
document.getElementById("passwordAlert").style.display = 'block';
document.getElementById("passwordAlert").innerHTML = ":( Both passwords must match.";
}
} else {
document.getElementById("passwordAlert").style.display = 'block';
document.getElementById("passwordAlert").innerHTML = ":( The password must be at least 6 characters long.";
}
}
</script>
<?php $attributes = array('name' => 'Form1','onsubmit' => 'return validate()');
echo form_open("visitor/confirm", $attributes);?>
<table>
<tr class='signup'>
<td class='signup1'>Password*</td>
<td class='signup2'>:</td>
<td class='signup3'>
<input id="pass1" onkeyup="chkpassword()" class="signup" type="password" value="" maxlength="20" name="password" />
</td>
</tr>
<tr class='signup'>
<td class='signup1'>Confirm Password*</td>
<td class='signup2'>:</td>
<td class='signup3'>
<input id="pass2" onkeyup="chkpassword()" class="signup" type="password" value="" maxlength="20" name="chkpassword" />
<div id="passwordAlert"></div>
</td>
</tr>
</table>
<input type="submit" value="Daftar">
<?php echo form_close();?>
(i'm passing nothing to this view)
if i made mistakes on password input, the div won't come out
then, if i inspect element and look into the console on chrome, it said that the onkeyup get Uncaught TypeError: Object is not a function error
what i've missed?
why it was ok when it runs on jsfiddle?
i change the confirm password name (chkpassword) since it was the same name as the js function.
<input id="pass2" onkeyup="chkpassword()" class="signup" type="password" value="" maxlength="20" name="chkpassword" />
<input id="pass2" onkeyup="chkpassword()" class="signup" type="password" value="" maxlength="20" name="chkpasswordx" />
credit to #Sumurai8