I'm creating a form and validating it with JS. I want to make the email id optional. Either i can be left blank or filled. But i want to validate the email id only if the something's typed in the field. And i must use regexe.
"email":{
"regex":"/^([\.a-z0-9_\-]+[#][a-z0-9_\-]+([.][a-z0-9_\-]+)+[a-z]{1,4}$)/i",
"alertText":"* Invalid email address"}
What are the changes should me made here?
You'd have to do a two step validation I think. Apply a different validation check for the email field if its empty.
Since it's Javascript can you do something like:
if (str === '') {
validations['email'] = {}
} else {
validations['email'] = {
// email validation
}
}
I don't know of any other way to do it then that. Maybe there's something you can do with a regex like a condition check but considering how regex work I don't think that it is possible.
Try this
var $email = $('form input[name="email'); //change form to id or containment selector
var re = /[A-Z0-9._%+-]+#[A-Z0-9.-]+.[A-Z]{2,4}/igm;
if ($email.val() != '' && !re.test($email.val()))
{
alert('Please enter a valid email address.');
return false;
}
Try it :
if(email.length > 0) {
//Test Email is Valid Or Not
}
Final code :
<html>
<head>
</head>
<body>
Enter Email : <input type="text" id="txt">
<button onclick="isValid()">Test</button>
<script>
var ele = document.getElementById("txt");
function isValid(){
var email = ele.value;
var patt = /^[a-zA-Z0-9_\-]+#[a-zA-Z0-9_\-]+\.[a-z]{1,4}$/i;
if(email.length > 0) {
if(patt.test(email))
alert("Valid Address Email");
else
alert("Invalid address Email");
}
else
alert("Email is Empty : Valid Address Email");
}
</script>
</body>
</html>
Check links
<input style="margin-top: 20px;" type="text" placeholder="Enter an Email ID" name="Email" id="Email" pattern="((\w+\.)*\w+)#(\w+\.)+(com|kr|net|us|info|biz)" required="required">
Related
Hey so uh I have a project due in a few days which requires us to make a contact page where someone can enter a name, email address, subject and message. We need to create javascript to make sure all fields are filled in and that the email is valid.
I have written the HTML for the form, as well as the javascript but I have 2 problems:
No error message displays when no message is entered in the memo field
The email field will not accept a valid email
I have tried to change the ID tag for the email but it automatically allows me to submit straight away without entering any data, I'm quite stuck.
Yes, they are both in two separate documents.
Note: I have not included all the code for the contact page, just the relevant form.
Thank you so much
Here are the images of my code:
HTML for contact page:
Javascript for Contact page:
function checkForm(){
var isValid = true;
var name = document.forms['contact']['name'].value;
var email = document.forms['contact']['emailaddress'].value;
var emailpattern = /\S+#\S+\.\S+/;
var subject = document.forms["contact"]["subject"].value;
var textarea = document.forms["contact"]["memo"].value;
console.log(name, email, subject, textarea);
if(name == ""){
document.getElementById('namemessage').innerHTML = "PLEASE enter a name";
isValid = false;
} else {
document.getElementById('namemessage').style.display = "none";
}
if(!emailpattern.test(emailaddress)){
document.getElementById('emailmessage').innerHTML = "PLEASE enter a valid email";
isValid = false;
}
else {
document.getElementById('emailmessage').style.display = "none";
}
if(subject == ""){
document.getElementById('subjectmessage').innerHTML = "PLEASE enter a subject";
isValid = false;
} else {
document.getElementById('subjectmessage').style.display = "none";
}
if(memo == ""){
document.getElementById('memomessage').innerHTML = "PLEASE enter your request";
isValid = false;
} else {
document.getElementById('memomessage').style.display = "none";
}
return isValid;
}
<main><form action="thankyou.html" name="contact" onsubmit="return checkForm()">
<label for="name">Name:</label>
<input type="text" id="name">
<p id="namemessage"></p><br><br>
<label for="emailaddress">Email Address:</label>
<input type="text" id="emailaddress">
<p id="emailmessage"></p><br><br>
<label for="subject">Subject:</label>
<input type="text" id="subject"><p id="subjectmessage">
</p><br><br>
<label for=memo>Message:</label><br><br>
<textarea id="memo" placeholder = "please type your message here.">
</textarea>
<br><p id="memomessage"></p><br><br>
<input type="submit" value="Submit">
</form>
</main>
No error message displays when no message is entered in the memo field
Because you have:
var textarea = document.forms["contact"]["memo"].value;
...
if (memo == "") {
Change textarea to memo.
The email field will not accept a valid email
Because you have:
var email = document.forms['contact']['emailaddress'].value;
...
if (!emailpattern.test(emailaddress)) {
Change emailaddress to email.
Fix those issues and it "works".
I need to validate a field in my the Facebook Registration plugin. I need to ensure that no special characters or spaces are used on the handle field. The preg_match works great with php but not sure how do do with with Javascript.
This is what I have for my if statement. Even when I used the proper text for the handle field it still comes up invalid.
var thisRegex = new RegExp('^(_|([a-z]_)|[a-z])([a-z0-9]+_?)*$/i');
if(!thisRegex.test(form.handle)){
errors.handle = "No spaces or special characters.";
}
Here is the full form code:
{"name":"name"},
{"name":"handle", "description":"Username - Letters & Underscores Only", "type":"text"},
{"name":"email"},
{"name":"country", "description":"Country", "type":"select", "options":{"United States":"United States","Canada":"Canada","Other":"Other"}},
{"name":"password"},
]'
redirect-uri="http://www.mystoragelink.com"
width="320"
onvalidate="validate">
</fb:registration>
<script>
function validate(form) {
errors = {};
var thisRegex = new RegExp('^(_|([a-z]_)|[a-z])([a-z0-9]+_?)*$/i');
if(!thisRegex.test(form.handle)){
errors.handle = "No spaces or special characters.";
}
return errors;
}
</script>
<head>
<script>
function ValidateForm()
{
var fname =document.getElementById('fname').value;
var lname=document.getElementById('lname').value;
var email= document.getElementById('email').value;
var pwd=document.getElementById('pwd').value;
//var email= document.getElementById('email');
if(email!='')
{
var filter = /^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
if (filter.test(document.getElementById('email').value)) {
return true;
}
else
{
alert('Please provide a valid email address');
document.getElementById('email').focus();
return false;
}}
if(fname == '')
{
alert("plz enter your firstname");
return false;
}
else if(lname == '')
{
alert("plz enter your lastname");
return false;
}
else if(email == '')
{
alert("plz enter your email address");
return false;
}
// var filter = /^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
// else if (!filter.test(document.getElementById('email').value;))
// {
// alert('Please provide a valid email address');
// email.focus;
// return false;
//}
else if(pwd == '')
{
alert("plz enter your password");
return false;
}
}
</script>
</head>
<form action="login.php" method="POST">
<table border="1">
<tr>
<tr><td>First Name:</td><td><input type="text" name="fname" id="fname"></td></tr><br>
<tr><td>Last Name:</td><td><input type="text" name="lname" id="lname"></td></tr><br>
<tr><td> Email:</td><td><input type="text" name="email" id="email"></td></tr><br>
<tr> <td>Password:</td><td><input type="password" name="pwd" id="pwd">`enter code here`</td></tr><br>
<tr><td><input type="submit" value="Insert"onclick="return ValidateForm();"></td></tr>
</tr>
</form>
**I think this will help You**
Thanks for your efforts. I was able to find my problem.
in the var the last /i of the RegExp('^(|([a-z])|[a-z])([a-z0-9]+_?)*$/i') needed to be removed.
Reference: https://developer.mozilla.org/en/docs/Web/JavaScript/Guide/Regular_Expressions
Here is the working code:
var thisRegex = new RegExp("^(_|([a-z]_)|[a-z])([a-z0-9]+_?)*$");
if(!thisRegex.test(form.handle)){
errors.handle = "No spaces or special characters.";
}
I have a login form in which the user enters the username and the password in an attempt to login to his profile. I want to dynamically verify that both the fields are filled before i start doing the server side processing.
<form id="form" method="post" action="student.jsp">
<label><strong>Username :</strong><br/><br/>
<input type="text" value="" name="username" id="idusername">
</label><br/><br/>
<label><strong>Password :</strong><br/><br/>
<input type="text" value="" name="password" id="idpassword">
</label><br/><br/><br/>
<input id="minibutton" name="send" type="submit" value="Login" />
</form>
I am using javascript which correctly verifies and alerts whenever the username is left blank and we attempt to login. However, it does not do so with the password field and we can get away with it being left blank.
$(document).ready(function(){
//global vars
var form = $("#form");
var username= $("#idusername");
var password = $("idpassword");
//On Submitting
form.submit(function(){
if(username.val().length==0 || password.val().length==0){
alert('Please enter the username');
return false;
}
else
{
if(password.val().length==0)
{
alert('Please enter the password');
return false;
}
else
return true;
}
});
});
I am not good at javascript but i need to use it for dynamic validation. Plaese pointy out the error in verifying the password field.
The missing hash symbol:
var password = $("idpassword");
should be:
var password = $("#idpassword");
change var password = $("idpassword"); to var password = $("#idpassword");
also in your logic:
if(username.val().length==0 || password.val().length==0){
alert('Please enter the username');
return false;
}
else{
if(password.val().length==0)
{
alert('Please enter the password');
return false;
}
else
return true;
}
if either the user name or password is empty, its always going to say "please enter the username" as it matches the if clause,
you should change it to 2 if's
if(username.val().length==0){
alert('Please enter the username');
return false;
}
if(password.val().length==0){
alert('Please enter the password');
return false;
}
return true;
That way, it checks if the user name is filled, then if the password is filled, if they both are, return true, else, if one is empty, it will flag it being empty and return false.
Hope this helps
First: I'm JavaScript newbie.
So.. I have basic form with password, repeat password, email and repeat email fields. I want to check if password is equal to repeat password. If it's not, alert message appears and page reloads. Same for email and repeat email.
BUT if pass and repeat password aren't equal AND email and repeat email aren't equal, first alert message appears, then the second message (this time for email) appears too fast. I want to show only one alert message when both fields don't match.
<script type="text/javascript">
function checkFields() {
var pass= document.getElementById('password');
var reppass= document.getElementById('reppass');
var email= document.getElementById('email');
var repemail= document.getElementById('repemail');
if (pass.value != reppass.value) {
alert('Passwords dont match');
window.location.reload();
}
if (email.value != repemail.value) {
alert('Emails dont match');
window.location.reload();
}
else if (pass.value != reppass.value && email.value != repemail.value) {
alert('Both fields dont match');
window.location.reload();
}
}
</script>
And the form:
<form onSubmit="checkFields()">
<p><label>Password:</label> <input name="password" id="password" required="true" type="password" /></p>
<p><label>Repeat password:</label> <input name="reppass" id="reppass" required="true" type="password" /></p>
<p><label>Email:</label> <input name="email" id="email" required="true" type="email" /></p>
<p><label>Repeat Email:</label> <input name="repemail" id="repemail" required="true" type="email" /></p>
<p><input type="submit" value="Send"></p>
</form>
You can simply return from the if clauses like this:
function checkFields() {
var pass = document.getElementById('password');
var reppass = document.getElementById('reppass');
var email = document.getElementById('email');
var repemail = document.getElementById('repemail');
if (pass.value != reppass.value && email.value != repemail.value) {
alert('Both fields dont match');
window.location.reload();
}
if (pass.value != reppass.value) {
alert('Passwords dont match');
window.location.reload();
return;
}
if (email.value != repemail.value) {
alert('Emails dont match');
window.location.reload();
return;
}
}
I like this style, because it prevents nesting if clauses. The downside is, that you have multiple return points that can be confusing - this heavily depends on the length of the function.
EDIT
Updated order of if blocks
if( condition1 ) {
}else if( condition2 ) {
}else{
…
}
I believe this is what you want.
One solution would be to break the validation up into separate methods, then only run the second validation if the first one succeeds.
Here's an example:
var FormValiditor = function() {
var pass = document.getElementById('password');
var reppass = document.getElementById('reppass');
var email = document.getElementById('email');
var repemail = document.getElementById('repemail');
return {
checkFields: function() {
if(checkPassword()){
return checkEmail();
}
return false;
},
checkPassword: function() {
if (pass.value != reppass.value) {
alert("Password don't match");
return false;
}
return true;
},
checkEmail: function() {
if(email.value != repemail.value){
alert("Emails do not match");
return false
}
return true
}
}
}();
Then, if you're using jQuery(which you should be!) you can run validation when the form gets submitted.
$('form').submit(FormValidator.checkFields);
if ...
else if ...
else if ...
...
else ...
That's how it should be structured. You can have as many else ifs as you like.
Please help me. The validation is not working:
<script type="text/javascript" src="javascript.js">
function validation()
{
var fname=document.forms["form1"]["fname"].value;
var lname=document.forms["form1"]["lname"].value;
var idnumber=document.forms["form1"]["idnumber"].value;
var email=document.forms["form1"]["email"].value;
var atpos=email.indexOf("#");
var dotpos=email.lastIndexOf(".");
var address=document.forms["form1"]["address"].value;
var phonenumber=document.forms["form1"]["phonenumber"].value;
if (fname==null || fname=="")
{
alert("Name should be entered correctly");
return false;
}
if (lname==null || lname=="")
{
alert("Name should be entered correctly");
return false;
}
if (isNaN(idnumber))
{
alert("Please enter a valid id number");
return false;
}
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length)
{
alert("Please enter a valid e-mail address");
return false;
}
if(address==null || address=="")
{
alert("Please insert your address");
return false;
}
if (isNaN(phonenumber))
{
alert("Please enter a valid phone number");
return false;
}
}
</script>
<form name="form1" action="validation.php" method="post" onsubmit=" return validation(this);return false">
Firstname:<input type="text" name="fname"><br/>
Lastname:<input type="text" name="lname"><br/>
Nation ID Number:<input type="text" name="idnumber" minlength="8"maxlength="8"><br/>
Email address: <input type="text" name="email"><br/>
Address:<input type="text" name="address"><br/>
Pnone number:<input type="text" name="phonenumber"><br/>
<input type="reset" name="reset" value="reset">
<input type="submit" name="submit" value="submit">
</form>
There are a number of issues with that code:
You really should not use the same <script> element for both calling src="javascript.js" and at the same time declare a function. Use separate elements, like this:
<script type="text/javascript" src="javascript.js"></script>
<script type="text/javascript">
function validation()
{
...
}
</script>
In the <form> element, there's a redundant ;return false. The form will take the value from return validation(this), anything after it will be ignored. Also, no need of ";" when using in-line javascript.
You are passing passing this as argument to the validation() function, but validation is expecting no argument. Should be:
function validation(oForm)
If you are already passing this, why not use it? this is a reference to the element itself, so it is, for the validation function, a reference to the form. So no need to name the form.
<form action="validation.php" method="post" onsubmit="return validation(this)">
And the references in function would be:
function validation(oForm)
{
var fname=oForm["fname"].value;
var lname=oForm["lname"].value;
}
Those changes alone could solve your problem. I'll check the code further to see if there is something else.
EDIT:
I've tested the validation now, and it works. The only required modification is removing the scr=validation.js from your <SCRIPT> tag. Use separate tags for that, as i suggested.
But i strongly suggest you consider the other issues I've mentioned.
Also, other suggestions regarding the validation itself:
For alphanumerical fields, no need to check for null, only "" is enough. You can simply use:
if (lname=="")
First Name and Last Name error messages are the same. That will confuse users.
Avoid testing phone numbers as numeric. Remember "(407) 234-5678" is a perfectly valid phone number, although it will fail your test. Unless you have a strong reason to treat it as numeric (automatic dialing?), leave it as an ordinary, text field.
In the National ID field: There is no minlength in HTML. Only maxlength
isNaN(idnumber) will return true if value is blank. And also if length<8. I assume it is a required field with a required length, so you should use:
if (isNaN(idnumber) || idnumber.length != 8)
{
alert("Please enter a valid id number");
return false;
}
For all your tests, consider trimming the values. Currently, input like " " (blanks only) WILL pass your test. Javascript has no built-in trim function, but it can be done with this:
function trim( texto ) {
return texto.replace(/^\s*|\s*$/g, "");
}
And used like this:
var fname=trim(oForm["fname"].value);
For clarity, use an explicit return true; in validation() after all tests successful.
Here is the suggested code after all changes:
<script type="text/javascript" scr="validation.js"></script>
<script type="text/javascript">
function validation(oForm)
{
var fname = trim(oForm["fname"].value);
var lname = trim(oForm["lname"].value);
var idnumber = trim(oForm["idnumber"].value);
var email = trim(oForm["email"].value);
var atpos = email.indexOf("#");
var dotpos = email.lastIndexOf(".");
var address = trim(oForm["address"].value);
var phonenumber = trim(oForm["phonenumber"].value);
if (fname=="")
{
alert("First name should be entered");
return false;
}
if (lname=="")
{
alert("Last name should be entered");
return false;
}
if (isNaN(idnumber) || idnumber.length != 8)
{
alert("Please enter a valid id number");
return false;
}
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length)
{
alert("Please enter a valid e-mail address");
return false;
}
if(address=="")
{
alert("Please insert your address");
return false;
}
if (isNaN(phonenumber))
{
alert("Please enter a valid phone number");
return false;
}
return true;
}
function trim( texto ) {
return texto.replace(/^\s*|\s*$/g, "");
}
</script>
<form name="form1" action="validation.php" method="post" onsubmit="return validation(this)">
Firstname:<input type="text" name="fname"><br/>
Lastname:<input type="text" name="lname"><br/>
Nation ID Number:<input type="text" name="idnumber" maxlength="8"><br/>
Email address: <input type="text" name="email"><br/>
Address:<input type="text" name="address"><br/>
Pnone number:<input type="text" name="phonenumber"><br/>
<input type="reset" name="reset" value="reset">
<input type="submit" name="submit" value="submit">
</form>