This is my email address validation code using JavaScript. The alert messages are correctly working but when I submit giving a valid email address it alerts 'Please provide a valid email address'. Please help me.
if(email=="")
{
alert("Enter emailid");
$("#email").focus();
return false;
}
else if(email!="")
{
var filter = /^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
if (!filter.test(email.value))
{
//alert(email)
//alert(filter.test(email.value))
alert('Please provide a valid email address');
email.focus();
return false;
}
}
Not a direct answer to your question...but can you not use HTML5 email input for this purpose? Why write javascript code for email validation when the browser can handle it? Use something like this:
<input type="email" name="email">
There are many advantages to using this including on-screen keyboard to match it (adds # and .com options).
For different types of HTML5 input types, refer this: http://www.w3schools.com/html/html5_form_input_types.asp
Try this
function ValidateEmail(){
var email = $('#txtemail').val();
if(email=="")
{
alert("Enter emailid");
$("#txtemail").focus();
return false;
}
else if(email!="")
{
var filter = /^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
if (!filter.test(email))
{
//alert(email)
//alert(filter.test(email.value))
alert('Please provide a valid email address');
$('#txtemail').focus();
return false;
}
}
}
Call the function ValidateEmail on the onclick event of your button. And also please note that you are doing something wrong with this line
if (!filter.test(email.value))
change this to be
if (!filter.test(email))
hope this helps.
Working DEMO
There is a small mistake in your code, which makes the alert to display.
Please look for this line in your code
if (!filter.test(email.value))
and replace with
if (!filter.test(email))
Variable Email holds the value of Email field of your form.
And another change would be, look for this line
email.focus();
and change this one to
$("#email").focus();
Related
I wrote the code for form field validation in JavaScript,
but it's not working properly as my requirement.
URLs only support:
http
https://
and (www.xyz.com , xyz.com ,xyz.co.in )
My code :
var file_url = document.getElementById(url);
if(file_url.value.match(^(http:\/\/www\.|https:\/\/www\.|http:\/\/|https:\/\/)[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(:[0-9]{1,5})?(\/.*)?$)){
alert('Please Enter valid Url');
return false;
}
but it does not work as expected
^(http:\/\/www\.|https:\/\/www\.|http:\/\/|https:\/\/)?[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(:[0-9]{1,5})?(\/.*)?$
Try this.See demo.
https://regex101.com/r/tX2bH4/58
After many trails i got this one better,I have tried this one working perfectly.I think this one also correct one.
if(!file_url.value.match(/(^|\s)((https?:\/\/)?[\w-]+(\.[\w-]+)+\.?(:\d+)?(\/\S*)?)/gi)){
alert('Please Enter valid Url');
return false;
}
Here is the demo: Demo of regex
I'm trying to use custom validation in my form. I know how to write the code for it. But i don't know how i can make available my new "password" custom validation in VTYPE.
Ext.apply(Ext.form.VTypes, {
password: function(val, field) {
if (field.initialPassField) {
var pwd = Ext.getCmp(field.initialPassField);
return (val == pwd.getValue());
}
return true;
},
passwordText: 'What are you doing?<br/>The passwords entered do not match!'
});
just tell me where i should write this "Password function" to achieve custom validation.
Thank you
Include these config in your password field.
vtype: 'password'
or confirm me whether you are validating two password fileds, whether same passwords
entered should match?
You have not provide any details of issue you are facing. That may help. You can create a separate js file for all custom vtypes and initialize this after ExtJS library code.
Updated my previous post with code example:
Ext.onReady(function(){
validationModule = function(){
//here you can define your custom vtypes
};
validationModule();
});
Best!!
I tried to write a regular expression to work with the position-absolute jQuery validation plugin to give error if the string is left empty OR its a invalid URL. It works well for the URl but doesn't give error if a empty string is there . Here's the regex
"regex": /^\S$|^(http[s]?:\/\/){0,1}(www\.){0,1}[a-zA-Z0-9\.\-]+\.[a-zA-Z]{2,5}[\.]{0,1}/,
Can somebody tell what's wrong in the regex?
EDIT:
I'm using this plugin for jQuery validation
Demo: Go to this URL and in the URL validtion section, remove HTTP and see the error messages
http://www.position-relative.net/creation/formValidator/demos/demoValidators.html
When I add required and URL validators together, it shoots 2 errors. But with only URL
validator, it doesn't say that its a Invalid URL. I just need 1 error for both Empty and
Invalid URL.
https://github.com/posabsolute/jQuery-Validation-Engine
Thanks
You can set the same generic error message for all errors using data-errormessage, so regardless of whether the field is empty or has an invalid value you will get the same message.
have you tried jQuery URL validation metohod ?
I wrote a small example how you could validate a email realy quick and easy. Without the hassle of using a plugin. If you use it just once you could just use
var emailaddressVal = 'nobody#example.cpom';
var emailReg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
if(emailReg.test(emailaddressVal) && emailaddressVal.length > 0)
{
alert('Your email is valid.');
}
else
{
alert('The email is invalid')
}
However putting it in a function so you could use it multiple times. than put it in a function for example:
// Email check function
function checkEmail(email)
{
var emailReg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
if(emailReg.test(email) && email.length > 0)
{
return true;
}
else
{
return false;
}
}
// Ussage
if(checkEmail('nobody#example.com'))
{
alert('SUCCESS!!');
}
else
{
alert('FAILED!!');
}
I have an html file which contains a form. There is lots of text typed input control need customer to input information. How do I check whether the customer's input is correct?
For example, I want to check if the username only contains digits, letters and '_'.
Please help me.
I'd appreciate if somebody can provide me a demo.
Thanks in advance!
Here’s one possible approach, for a simple task like the one given as example:
<script>
function check(elem) {
if(elem.value.match('^' + elem.getAttribute('pattern') + '$')) {
return true;
} else {
alert(elem.getAttribute('data-msg'));
return false;
}
}
</script>
<input name=username pattern=[a-zA-z0-9_]{1,9} onblur=check(this)
data-msg="The user name may only contain letters A–Z, digits, and underlines and must be 1 to 9 characters.">
The idea here is to start with the HTML5 pattern attribute, specifying the allowed pattern of data as a regular expression. It already works on several modern browsers and does no harm when it doesn’t. Then you add an event attribute, which causes a JavaScript-driven check to be made, using the regular expression taken from the same attribute (with a prefix and postfix character added so that the check is made on the input item as a whole).
You may wish to display the error message in some less disruptive manner than via alert()
<input type="text" id="username" />
<span id="invalidMessage" style="display:none; color:Red"><img src="../../Images/error.gif" alt="OK" />invalidEmail。</span>
<script type="text/javascript">
$(document).ready(function() {
$('#username').blur(function() {
$('#invalidMessage').hide();
if ($('#username').val() != "") {
var email = /_*\w+(-?\w+)*#_*\w+(-?\w+)*(._*\w+(-?\w+)*)*.\w*/;
if (!email.test($('#username').val())) {
$('#invalidMessage').show();
}
}
});
});
</script>
There is a demo,hope can help you.
I would use something like this on the client side;
<script type="text/javascript">
<!--
function validate_form ( )
{
valid = true;
if ( document.contact_form.contact_name.value == "" )
{
alert ( "Please fill in the 'Your Name' box." );
valid = false;
}
return valid;
}
//-->
</script>
Then, i would use more robust error checking on the server side to ensure you have valid data. If you can catch bad data at the client, its a plus, as it avoids the hit on the server, but the validation really belongs on the data on the server side, as its more secure and can be reused by other forms.
I have a textbox where the user is required to insert a valid email address.
When the user submits a valid email address a loading graphic appears while the data is posted back.
The code below works fine for showing the loading graphic but it does not check that the email address is valid first. Can anyone help out?
$('#btnEmail1Submit').live ("click", function() {
$('<div class="submitBg"></div>').appendTo(".emailEditContainer");
$('<div class="submitLoadingCont"><img class="submitLoading" src="images/mypreferences/loading.gif" width="50" height="50" /></div>').appendTo(".emailEditContainer");
});
I am thinking that I need to put an if statement around the function that is run on click - so something like:
$('#btnEmail1Submit').live ("click", function() {
if(emailvalid == true) {
$('<div class="submitBg"></div>').appendTo(".emailEditContainer");
$('<div class="submitLoadingCont"><img class="submitLoading" src="images/mypreferences/loading.gif" width="50" height="50" /></div>').appendTo(".emailEditContainer");
}
});
I am using asp.net email validation - it looks something like this:
<asp:RegularExpressionValidator Display="Dynamic" ValidationGroup="PrimarySubmit" ID="RegularExpressionValidator1" runat="server" ValidationExpression="\w+([-+.']\w+)*#\w+([-.]\w+)*\.\w+([-.]\w+)*" ControlToValidate="tbEmail1" ErrorMessage="Invalid email address - " />
You will need to use a regex to test the email address for validity:
function isValidEmailAddress(emailAddress) {
var pattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(#((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(#\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
return pattern.test(emailAddress);
};
That came from this question, so see that thread for more info.
You need to call that function with the email address provided by the user, so I'm assuming something like:
var email = $("#emailInput").val();
if(isValidEmailAddress(email)) {
//Do stuff
}
You should check the email validity using a regexp
var 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,}))$/
$('#btnEmail1Submit').live ("click", function() {
if(!email.match(re)) {
alert('invalid email');
return false;
}
$('<div class="submitBg"></div>').appendTo(".emailEditContainer");
$('<div class="submitLoadingCont"><img class="submitLoading" src="images/mypreferences/loading.gif" width="50" height="50" /> </div>').appendTo(".emailEditContainer");
});
The regexp comes from Validate email address in JavaScript?
Email validation has been discussed many, many times on SO, and elsewhere. In short it's hard (impossible) to do perfectly and is a trade off between maximising coverage of valid formats and minimising false positives. In fact all i do to validate email addresses is a basic sanity check. In pseudocode:
if (address.contains("#")) {
.. // then ok
}
Anything else is basically futile. Even if you spend ages constructing some insanely complex regex to comply with RFC822 to get most valid addresses (there are real addresses that don't comply with the RFC) - how do you know this inbox actually exists?
you can check this
function myClick() {
Page_ClientValidate();
if (Page_IsValid) {
return true;
}
else {
return false;
}
}
if you are using regularexpression validator then this can be used....
If you need to execute the aps validator to validate the email address, which seems to be pertinant to your question, then you need to call the generated javascript that does this before you make the call - so call:
if(Page_ClientValidate)
do your other stuff
However, this will run all of the page validation, not just the email.
If you need to only run the one validation call for this, you can look at the generted javascript on your page, and find where it does the call for your email validation, and call that. However, I would not recommend that, as it may change when the page is regenerated.
See CodeProject