This question already has answers here:
How can I validate an email address in JavaScript?
(79 answers)
Closed 8 years ago.
I am very new to coding so go easy.
I am trying to make a email validation form but it needs to reject a blank cell (input box) sorry for being so bad at coding..... i also was going to use a regex
it has to be alpanumeric#alpanumeric.alpanumeric
sorry
The correct behavior in this case would be to perform a "pre-check" on fields before actually executing some more complex validation (eg: regular expressions).
The logic would look something like this:
valid_email = false;
email = strip_leading_trailing_spaces( email ); // don't forget to cleanup user input
if ( email != "" ) {
// perform regex testing here, set valid_email to false if failed
}
// handle "valid_email" variable here
It's worth noting here that any client side validation should be duplicated to/re-checked on the server as any user with a little knowledge in JS could easily bypass any validation done on the clients computer.
You don't need a regex if you are just checking to see if it's empty:
<input type=text id=email><button onClick="validate()">Validate</button>
<script language="javascript">
function validate() {
if ($("#email").val().length == 0) {
alert("Enter an email address");
}
}
</script>
with a regexp :
var valid_email = ! email.match( /^\s*$/ ) ;
If there's only spaces and tabs or nothing then valid_email = false
demo : http://regex101.com/r/iX8lF7/1
Related
I am having some problem in JavaScript form validation.
I have some optional fields in my HTML code. On submit, they don't need to be filled up but if the user provides some input they must be verified. For instance, I have an optional phone number field. If the user provides an input then I need to check if they are all numbers.
How could I do that?
You need only invoke the validation code if the field value meets some precondition, in this case: if the field has a value (checked by testing the length property of the string value):
var fieldValue = document.getElementById("someInput").value;
if( fieldValue.length > 0 ) {
if( someValidationFunction( fieldValue ) ) alert("Field is invalid");
}
What's stopping you from using HTML5's own validation?
<input type="tel" pattern="[0-9]+" />
No JavaScript required, will work on all modern browsers.
A note on security: Please don't rely on client-side validations for security concerns, as they can be trivially disabled. All validation should also be done server-side.
you can bind your custom method as a callback to your submit action in your form
<form onSubmit="return customValidation()>
In the method do your validations.
function customValidation()
{
//code to test fields
fieldToValidate = document.getElementById("field-id")
//validate the field
}
You can't use the other answers if you need it to be more secure; you shouldn't do this with JavaScript, because if a user for some reason has it turned off in their browser (or they turned it off on purpose) then the form won't still be verified. Instead you need to do it with PHP on the server. On the server that the form is being sent to you need to get the query strings sent with the form ($_GET['phonenumber'];), and see if it's a number (int intval ( mixed $phonenumber )). This should return NaN if it's not a number.
This question already has answers here:
How can I validate an email address in JavaScript?
(79 answers)
Closed 8 years ago.
I am having trouble with my email validation code using function validateEmail (str). Any suggestions?
//validates email address form
function validateEmail (str)
{
var retVal;
var atpos=retVal.indexOf("#");
var dotpos=retVal.lastIndexOf(".");
if (atpos<1 || dotpos<atpost+2 || dotpos+2>=retVal.length)
{
retVal = false;
return retVal;
}
Any suggestions? Yes. Don't.
<input type="email" />
Problem solved!
It should be noted that use of HTML5 features will make for a beautiful web... provided the browser supports it. The reason being, a failed validation will cause the browser to notify the user of the error in a non-intrusive and consistent, native manner.
Older browsers will not be able to validate in this way, however due to the specification stating that unrecognised type values should default to text, HTML5 is fully backwards compatible, way back into IE5.5 and almost certainly even earlier - maybe even IE1!
This lack of validation is not an issue. Validation should always be handled server-side, regardless of what validation you have on the client-side. As an example, in PHP, you would pass it through filter_var with the FILTER_VALIDATE_EMAIL filter.
The Problem of your code is that you create an empty variable (var retVal) and then you check this variable instead of the given string:
var retVal;
var atpos=retVal.indexOf("#");
var dotpos=retVal.lastIndexOf(".");
The correct code is
function validateEmail (str)
{
var retVal;
var atpos=str.indexOf("#");
var dotpos=str.lastIndexOf(".");
if (atpos<1 || dotpos<atpost+2 || dotpos+2>=str.length)
{
retVal = false;
return retVal;
}
// further code
}
I am doing email regular expression validation for the email and I am stuck on one point using
following expression if user enter something like abc.abc then this expression works fine but when user enters advxyz#pqr.com then it doesn't work
var myreg = new RegExp(/([a-z0-9.]+)#([a-z0-9]+)\.([a-z0-9]+)/i);
var patter = myreg.test(document.getElementById("email").value)
alert(patter)
if(patter == false){
errorMsg.push("email Formate Error Ex:firstname.lastname#abc.com");
}
I want that user must enter his email in this formate like firstname.lastname#abc.com/.ca/.org
var pattern = /^[a-z0-9]+\.[a-z0-9]+#[a-z0-9]+\.[a-z]+$/i;
pattern.test('firstname.lastname#abc.com');
// returns true;
pattern.test('jsmith#abc.com');
// returns false;
pattern.test("abc.abc");
// returns false;
Using Regular Expressions is probably the best way.
Here's an example
(live demo):
function validateEmail(email) {
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,}))$/;
return re.test(email);
}
But keep in mind that one should not rely only upon JavaScript validation. JavaScript can easily be disabled. This should be validated on the server side as well.
Source
This work Perfectly for me.
/^[a-zA-Z]([a-zA-Z0-9_\-])+([\.][a-zA-Z0-9_]+)*\#((([a-zA-Z0-9\-])+\.){1,2})([a-zA-Z0-9]{2,40})$/;
Hope this is helpful in resolving the issue \b[A-Z0-9._%-]+#[A-Z0-9.-]+.[A-Z]{2,4}\b
Its case sensitive.
Pattern for to validate email address is:
/^([a-zA-Z0-9_.-])+\#(([a-zA-Z0-9-])+.)+([a-zA-Z0-9]{2,4})+$/;
use this pattern in Regex. and you can validate any email..
I have a form with 2 number inputs and I am trying to validate it using the jQuery Validation plugin. I want to allow the form to be submitted only if the sum of the values is less than or equal to 10. For example, I want to allow 3 and 6, but not 7 and 8. How can I do this?
I was able to come up with something that works but I think it is inelegant and fragile to arbitrarily apply the rule to one input and use an attribute on that input to refer to the other input. I looked in the documentation for the plugin and I don't see any way of defining a validator that is meant to be used on more than one input. Can anyone think of a simpler way?
As far as the jquery validation plugin. No. A simpler way. Yes write your own in plain javascript.
function mySubmitfuntcion()
{
var myvar1 = document.GetElementById("1").value;
var myvar2 = document.GetElementById("2").value;
if(myvar1 + myvar2 <= 10) {
return true;
}
else {
alert("Please enter valid values");
return false;
} // end if
} // end function
returning false stops the mySubmitfunction() from completing.
In my experience writing custom validation scripts works better because you have more control. Remember to add the validation function to a button or the forms onsubmit event.
I do understand the problems with validating emails but I wonder whether this would block anyone that has a legal email.
I was looking for a list of valid emails to test it myself but did not find any.
Anyone have an email that is valid but this regex thinks it's not?
emailRegex.test('Emailing#domain.aero')
Very long line:
emailRegex = /^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(#((?:[\w-]+\.)*\w[\w-]{0,66})\.(([a-z]{2}|AERO|ARPA|ASIA|BIZ|CAT|COM|COOP|EDU|GOV|INFO|INT|JOBS|MIL|MOBI|MUSEUM|NAME|NET|ORG|PRO|TEL|TRAVEL|XN--0ZWM56D|XN--11B5BS3A9AJ6G|XN--3E0B707E|XN--45BRJ9C|XN--80AKHBYKNJ4F|XN--90A3AC|XN--9T4B11YI5A|XN--CLCHC0EA0B2G2A9GCD|XN--DEBA0AD|XN--FIQS8S|XN--FIQZ9S|XN--FPCRJ9C3D|XN--FZC2C9E2C|XN--G6W251D|XN--GECRJ9C|XN--H2BRJ9C|XN--HGBK6AJ7F53BBA|XN--HLCJ6AYA9ESC7A|XN--J6W193G|XN--JXALPDLP|XN--KGBECHTV|XN--KPRW13D|XN--KPRY57D|XN--LGBBAT1AD8J|XN--MGBAAM7A8H|XN--MGBAYH7GPA|XN--MGBBH1A71E|XN--MGBC0A9AZCG|XN--MGBERP4A5D4AR|XN--O3CW4H|XN--OGBPF8FL|XN--P1AI|XN--PGBS0DH|XN--S9BRJ9C|XN--WGBH1C|XN--WGBL6A|XN--XKC2AL3HYE2A|XN--XKC2DL3A5EE0H|XN--YFRO4I67O|XN--YGBI2AMMX|XN--ZCKZAH|XXX)(?:\.[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;
Dominic Sayers has created a list of email edge cases that you could use to validate your test. You can find it here.
The valid address test#[IPv6:::], "test\ test"#iana.org or "test#io" are not accepted by your regex.
It's a beautiful expression, but soon to be relegated to the realm of obsolescence:
http://www.icann.org/en/topics/new-gtld-program.htm
Global Top Level Domains (yourbestfriend#worksfor.coke) are coming, and they'll break all of our scripts in a few years :)
Though, to answer your question, no, I was not able to break your email check using today's finite limit on "valid" domain extensions.
Here is the code for html input field and button field
<input input type="text" name="txtEmailId" id="txtEmailId" />
<input type="submit" class="button" value="Suscribe" name="Suscribe"
onclick="javascript:ShowAlert()" />
Now add the below function to the header of your page
<script type="text/javascript">
function ShowAlert() {
var email = document.getElementById('txtEmailId');
var filter = /^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
if (!filter.test(email.value)) {
alert('Please provide a valid email address');
email.focus;
return false;
}
else {
alert("Thanks for your intrest in us, Now you
will be able to receive monthly updates from us.");
document.getElementById('txtEmailId').value = "";
}
}
</script>
Here you can find the article on this Email Validation in JavaScript