There are similar questions, but I can't find the way I want to check the form submit data.
I like to check the form submit data for phone number and email. I check as follows, but it doesn't work.
How can I make it correct?
<script>
function validateForm() {
var x = document.forms["registerForm"]["Email"].value;
if (x == null || x == "") {
alert("Email number must be filled out.");
return false;
}
else if(!/#./.test(x)) {
alert("Email number must be in correct format.");
return false;
}
x = document.forms["registerForm"]["Phone"].value;
if (x == null || x == "" ) {
alert("Phone number must be filled out.");
return false;
}
else if(!/[0-9]+()-/.test(x)) {
alert("Phone number must be in correct format.");
return false;
}
}
</script>
For email I'd like to check only "#" and "." are included in the email address.
For phone number, I'd like to check ()-+[0-9] and one space are only accepted for phone number, for example +95 9023222, +95-1-09098098, (95) 902321. How can I check it?
There will be another check at the server, so there isn't any need to check in detail at form submit.
Email validation
From http://www.w3resource.com/javascript/form/email-validation.php
function ValidateEmail(mail)
{
if (/^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(myForm.emailAddr.value))
{
return (true)
}
alert("You have entered an invalid email address!")
return (false)
}
Phone number validation
From http://www.w3resource.com/javascript/form/phone-no-validation.php.
function phonenumber(inputtxt)
{
var phoneno = /^\d{10}$/;
if ((inputtxt.value.match(phoneno))
{
return true;
}
else
{
alert("message");
return false;
}
}
You can do something like this:
HTML part
<div class="form_box">
<div class="input_box">
<input maxlength="64" type="text" placeholder="Email*" name="email" id="email" />
<div id="email-error" class="error-box"></div>
</div>
<div class="clear"></div>
</div>
<div class="form_box">
<div class="input_box ">
<input maxlength="10" type="text" placeholder="Phone*" name="phone" id="phone" />
<div id="phone-error" class="error-box"></div>
</div>
<div class="clear"></div>
</div>
Your script
var email = $('#email').val();
var phone = $('#phone').val();
var email_re = /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,3}))$/;
var mobile_re = /^[0-9]{10}$/g;
if ($.trim(email) == '') {
$('#email').val('');
$('#email-error').css('display', 'block');
$('#email-error').html('Please enter your Email');
} else if (!email.match(email_re)) {
$('#email-error').css('display', 'block');
$('#email-error').html('Please enter valid Email');
}
if ($.trim(phone) == '') {
$('#phone').val('');
$('#phone-error').css('display', 'block');
$('#phone-error').html('Please enter your Phone Number');
} else if (!phone.match(mobile_re)) {
$('#phone-error').css('display', 'block');
$('#phone-error').html('Please enter valid Phone Number');
} else {
$('#phone-error').css('display', 'none');
$('#phone-error').html('');
}
You could of course write the validation part yourself, but you could also use one of the many validation libraries.
One widely used one is Parsley. It's very easy to use. Just include the .js and .css and add some information to the form and its elements like this (fiddle):
<script src="jquery.js"></script>
<script src="parsley.min.js"></script>
<form data-parsley-validate>
<input data-parsley-type="email" name="email"/>
</form>
HTML5 has an email validation facility. You can check if you are using HTML5:
<form>
<input type="email" placeholder="me#example.com">
<input type="submit">
</form>
Also, for another option, you can check this example.
Related
Hi I'm trying to make this code more clean. I struggle with arrays and loops and have no idea how to convert this into into a loop. This is javascript for a form on an html page and if they leave a field blank, when they hit submit it should return an alert box and if everything is submitted properly it should confirm with them. There's also a reg exp for an acceptable postal code entry.
function validate()
{
var register = document.forms[0];
if (register.fname.value === "")
{
alert("Please fill out your first name.");
return false;
}
else if(register.lname.value === "")
{
alert("Please fill out your last name.");
return false;
}
else if(register.address.value === "")
{
alert("Please fill out your address.");
return false;
}
else if(register.postal.value ==="")
{
alert("Please enter a valid postal code.");
return false;
}
else if(!checkPostal(register.postal.value))
{
alert("Please enter a valid postal code.");
return false;
}
else if(register.eAddress.value === "")
{
alert("Please fill out your email address.");
return false;
}
return confirm("Is the information correct?");
}
//postal code regExp
function checkPostal()
{
var myReg = /^[A-Z]\d[A-Z] ?\d[A-Z]\d$/ig;
return myReg.test(document.getElementById("postal").value);
}
You can make this a pure HTML solution if you want to reduce javascript:
inputs have a required attr ref
additionally, inputs have a pattern attr ref that supports regex.
This kind of solution lets the browser handle feedback
<form>
<label>first name:
<input type="text" name="fname" required
minlength="1">
</label><br/>
<label>last name:
<input type="text" name="lname" required
minlength="1">
</label><br/>
<label>postal code:
<input type="text" name="zip" required pattern="^[A-Z]\d[A-Z] ?\d[A-Z]\d$"
minlength="1">
</label><br/>
<input type="submit" />
</form>
$.each( $( "#input input" ), function( key, element ) {
if( !$(element).val() ) {
$( "#error" + key ).text( "Input " + $( element ).attr( "name" ) + " is required");
return false;
}
});
Set your message as attribute on each element of the form like this:
<form method="POST" action="submit.php">
<input id="item1" type="text" value="" data-message="My error message" data-must="true">
...//do the same for other elements...
</form>
Now loop like below
var elements = document.forms[0].elements;
for (var i = 0, element; element = elements[i++];) {
if (element.getAttribute("must") && element.value === ""){
alert(element.getAttribute("message"));
return false;
}
}
return confirm("Is the information correct?");
My javascript isn't running when I click submit on my form page.
<form onsubmit="validateReg()">
<p>
//email registration
<input type="text" id="e-mail" placeholder="Email" />
</p><p>
//password registration
<input type="text" id="pswd" placeholder="Password" />
</p>
<br>
<input type="submit" class="submit">
</for
I've tried multiple times linking the Javascript to the Html form and on the page when I click submit it doesn't return any of my error alerts.
//HTML
<form onsubmit="validateReg()">
<p>
<input type="text" id="e-mail" placeholder="Email" />
</p><p>
<input type="text" id="pswd" placeholder="Password" />
</p>
<br>
<input type="submit" class="submit">
</form>
//Javascript
//Main Function
function validateReg(){
var email = document.getElementById('e-mail').value;
var password = document.getElementById('pswd').value;
var emailRGEX = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/;
var emailResult = emailRGEX.test(email);
//validate Email
if(emailResult == false){
alert("Please enter a valid email address");
return false;
}
//validate lower case
var lowerCaseLetters = /[a-z]/g;
if(password.value.match(lowerCaseLetters)) {
return true;
}else{
alert("Password needs a lower case!");
return false;
}
//validate upper case
var upperCaseLetters = /[A-Z]/g;
if(password.value.match(upperCaseLetters)){
return true;
}else{
alert("Password needs an upper case!");
return false;
}
//validate numbers
var numbers = /[0-9]/g;
if(password.value.match(numbers)){
return true;
}else{
alert("Password needs a number!");
return false;
}
//validate special characters
var special = /[!##$%^&*(),.?":{}|<>]/g;
if(password.value.match(special)){
return true;
}else{
alert("Password needs a special character!");
return false;
}
if(password.value.length >=8){
return true;
}else{ alert("Password needs to be at least 8 characters");
return false;
}
}
I expect the code to output errors when a password is incorrectly submitted and when a password and email is correctly submitted so out put thank you.
As Oluwafemi put it you could put an event listener on your 'submit' event instead. I would put the event on the submit button though. That way you can stop it on the click event without having to fire the submit of the form. If you update your code it could help with troubleshooting in the future.
It wouldn't take much to modify your code either.
First, you would need to update your form to look like this:
<form id="form">
<p>
<input type="text" id="e-mail" placeholder="Email" />
</p>
<p>
<input type="text" id="pswd" placeholder="Password" />
</p>
<br />
<input id="submitButton" type="submit" class="submit">
</form>
Then add this below your javascript function like so:
document.querySelector("#submitButton").addEventListener("click", function(event) {
event.preventDefault;
validateReg()
}, false);
What this is doing is stopping the submit of the form and doing the check as expected. You can read more on this on the Mozilla developer site.
You will need to add document.getElementById('form').submit(); to any return statement that was set to true.
I did however, update the code to have the submit become the default functionality and the checks just return false if they fail like this:
//Javascript
//Main Function
function validateReg() {
var email = document.getElementById('e-mail').value;
var password = document.getElementById('pswd').value;
var emailRGEX = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/;
var emailResult = emailRGEX.test(email);
//validate Email
if(emailResult == false){
alert("Please enter a valid email address");
return false;
}
//validate lower case
var lowerCaseLetters = /[a-z]/g;
if(password.match(lowerCaseLetters) == null) {
alert("Password needs a lower case!");
return false;
}
//validate upper case
var upperCaseLetters = /[A-Z]/g;
if(password.match(upperCaseLetters) == null){
alert("Password needs an upper case!");
return false;
}
//validate numbers
var numbers = /[0-9]/g;
if(password.match(numbers) == null){
alert("Password needs a number!");
return false;
}
//validate special characters
var special = /[!##$%^&*(),.?":{}|<>]/g;
if(password.match(special) == null){
alert("Password needs a special character!");
return false;
}
if(password.length < 8){
return false;
}
document.getElementById('form').submit();
}
A better way to do this is to add an event listener to your js file and listen for the 'submit' event. Followed by your function.
Furthermore ensure that your js file is added to your script tag in your HTML file. That should work if your logic is correct.
I am making an HTML form with fields validation using JavaScript. I am stuck on email validation. I searched internet and found something like this-
JS Code
function validateemail() {
var x=document.myform.email.value;
var atposition=x.indexOf("#");
var dotposition=x.lastIndexOf(".");
if (atposition<1 || dotposition<atposition+2 || dotposition+2>=x.length) {
alert("Please enter a valid e-mail address \n atpostion:"+atposition+"\n dotposition:"+dotposition);
return false;
}
}
HTML Code
<body>
<form name="myform" method="post" action="#" onsubmit="return validateemail();">
Email: <input type="text" name="email"><br/>
<input type="submit" value="register">
</form>
Please explain me this?
Check this i am using something like this i minified some of them
You must Enter Valid Email address something like this Example#example.com
$(document).ready(function() {
$('.insidedivinput').focusout(function() {
$('.insidedivinput').filter(function() {
var emil = $('.insidedivinput').val();
var emailReg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
if (emil.length == 0) {
$('.fa-check').css('display', 'none');
$('.fa-close').css('display', 'inline');
$('.sendmailbuttontrigger').attr('disabled', 'disabled');
$('.SendEmail').attr('disabled', 'disabled');
} else if (!emailReg.test(emil)) {
$('.SendEmail').attr('disabled', 'disabled');
$('.sendmailbuttontrigger').attr('disabled', 'disabled');
$('.fa-check').css('display', 'none');
$('.fa-close').css('display', 'inline');
} else {
// alert('Thank you for your valid email');
$('.fa-close').css('display', 'none');
$('.sendmailbuttontrigger').removeAttr('disabled');
$('.fa-check').css('display', 'inline');
}
})
});
});
.fa-check{
display:none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type='email' class='insidedivinput'><i class='fa-check'>Validated</i><i class="fa-close">UnValidated</i>
<button class="sendmailbuttontrigger" disabled>
Send
</button>
If you just want to validate an email address, you can use the validation that's built into HTML:
<form onsubmit="return false;">
<input type="email" required="1">
<input type="submit">
</form>
(Leave out the onsubmit for your own form, of course. It's only in my example to keep you from leaving the page with the form.)
I also searched on the Internet and use this one and it's working.
// email validation
checkEmail = (inputvalue) => {
const pattern = /^([a-zA-Z0-9_.-])+#([a-zA-Z0-9_.-])+\.([a-zA-Z])+([a-zA-Z])+/;
if (pattern.test(inputvalue)) return true;
return false;
}
I am doing some form validation in JSP, on click on submit button "validate_access()" function is not called or not working. Sometimes this function displays a alret box and then stop doing any thing . Please tell what is wrong with this piece of code.Here is a piece of code:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Data management system</title>
<script language="JavaScript" type="text/javascript">
function validate_access()
{
var a = document.forms["myForm1"]["MISDN"].value;
var b = document.forms["myForm1"]["Issue"].value;
var c = document.forms["myForm1"]["SR"].value;
var d = document.forms["myForm1"]["date"].value;
var numbers = /^[0-9]+$/;
var alpha= /^[a-zA-Z]+$/;
var Datee= /^\d{1, 2}\/\d{1, 2}\/\d{4}$/;
if(document.myform1.MISDN.value=="" && document.myform1.Issue.value=="" && document.myform1.SR.value=="" && document.myform1.date.value=="")
{
alert("Manadotry fields should not left blank");
document.myform1.MISDN.focus();
document.myform1.Issue.focus();
document.myform1.SR.focus();
document.myform1.date.focus();
return false;
}
else if(!a.value.match(numbers))
{
alert('Please input numeric characters only');
document.myform1.MISDN.focus();
return false;
}
else if(!(b.value.match(numbers) && b.value.match(alpha)))
{
alert('Please input numeric and alphabets only');
document.myform1.Issue.focus();
return false;
}
else if(!c.value.match(numbers))
{
alert('Please input numeric characters only');
document.myform1.SR.focus();
return false;
}
else if(!d.value.match(Datee))
{
alert('Please input correct date');
document.myform1.date.focus();
return false;
}
else
return true;
}
</script>
</head>
<body>
<div class="main">
<div class="header"></div>
<div class="continer">
<div class="myform1" style="height:200px; width:300px; float:left;">
<h2>1344 Access</h2>
<form name="myform1" action="access.jsp" method="get" onsubmit="return validate_access()">
<br/>MSISDN:<input type="text" name="MISDN" maxlength="11">
<br/>Issue:<input type="text" name="Issue" maxlength="13">
<br/>SR:<input type="text" name="SR">
<br/>Date:<input type="text" name="date" value="dd/mm/yy">
<br/><input type="submit" value="Submit">
<br/><input type="reset" name="Reset">
</form>
</div>
<div class="myform2" style="float:left;height:200px; width:300px;">
<h2>O.C.S</h2>
<form name="myform2" action="ocs.jsp" method="post" onsubmit="return validate_ocs()">
<br/>MSISDN:<input type="text" name="MISDN" maxlength="11">
<br/>SR:<input type="text" name="SR">
<br/>REASON:<input type="text" name="reason">
<br/><input type="submit" value="Submit">
<br/><input type="reset" name="Reset">
</form>
</div>
</div>
</div>
</body>
Problems in your javascript are:
the first if condition check is wrong you mean || in place of &&.
then next when you call match method on empty string a error probably raise like:
Uncaught TypeError: Cannot read property 'match' of undefined
you calling .focus() continuously that doesn't making any sense, call once with a condition check.
There is something wrong in this line:var a = document.forms["myForm1"]["MISDN"].value;
Look at your source code, your form name is "myform1" not "myForm1".
JavaScript is case sensitive.
http://en.wikipedia.org/wiki/JavaScript_syntax
in your js:
document.forms["myForm1"]
but in your form(html) it is:
<form name="myform1"
Try this:
function validate_access()
{
var a = document.forms["myForm1"]["MISDN"].value;
var b = document.forms["myForm1"]["Issue"].value;
var c = document.forms["myForm1"]["SR"].value;
var d = document.forms["myForm1"]["date"].value;
var numbers = /^[0-9]+$/;
var alpha= /^[a-zA-Z]+$/;
var Datee= /^\d{1, 2}\/\d{1, 2}\/\d{4}$/;
if(a == "" && b == "" && c == "" && d == "")
{ //as you have default value for d (date field), this condition will never match;
//either you can remove default value or provide different logic
alert("Manadotry fields should not left blank");
document.myForm1.MISDN.focus();
document.myForm1.Issue.focus();
document.myForm1.SR.focus();
document.myForm1.date.focus();
return false;
}
else if(a == "" && !a.match(numbers))
{
alert('Please input numeric characters only');
document.myForm1.MISDN.focus();
return false;
}
else if(!(b.match(numbers) && b.match(alpha)))
{
alert('Please input numeric and alphabets only');
document.myForm1.Issue.focus();
return false;
}
else if(!c.match(numbers))
{
alert('Please input numeric characters only');
document.myForm1.SR.focus();
return false;
}
else if(!d.match(Datee))
{
alert('Please input correct date');
document.myForm1.date.focus();
return false;
}
else
return true;
}
Your mistakes:
(i) form name spelling mistake (caseSensitive)
(ii) you used HTMLElement.value.value to check (in if conditions)
For example:
var a = document.forms["myForm1"]["MISDN"].value;
a.value.match(numbers); // it simply means HTMLElement.value.value (which will never work)
working on php project want to do validation at once only at all fields of registration form.
fields
name
address
mobile
all above fields are mandatory so can i write only one function of validation
function validateForm()
{
if (document.myForm.name.value == "")
{
alert("Please enter the name");
document.myForm.name.focus();
return false;
}
if (document.myForm.address.value == "")
{
alert("Please enter the address");
document.myForm.address.focus();
return false;
}
...
}
instead of this how can i write only one function code so that i do not need to check all textbox values separately .
If you add Ids to your input fields...
<input type="text" name="name" id="name"/>
<input type="text" name="address" id="address"/>
<input type="text" name="mobile" id="mobile"/>
You can then do something like...
var Fields = [['name', 'your name'],
['mobile', 'your mobile number'],
['address', 'your address']]
for(x=0; x<Fields.length; x++) {
if(document.getElementById(Field[x][0]).value == '') {
alert('Please enter ' + Field[x][1]);
return false;
}
}