I am trying to validate an email address for a form element. I am familiar with regular expressions so I believe that part is correct, but I want it to display an alert when the email entered is invalid. My problem is that the form submits even when I enter an invalid email address instead of popping up the alert window.
RegEx function in javascript:
function validateEmail()
{
var myEmailRegEx = /\w+#\w+\.[a-z]|[A-Z]|\d|\.|-{2,}/
if(myEmailRegEx.test(document.getElementById("EmailAddress")))
{
return true;
}
else
{
alert("That is not a valid email address");
return false;
}
}
form HTML:
<input type="text" name="Email" id="EmailAddress" size="50" />
<br />
<input type="submit" value="Submit Email" onClick="validateEmail();" />
Just for the sake of clarity, the problem with what you were doing was that you were giving an object to the regex for testing, which always returns true(weird though). With the .value we get the string that the field holds and then test the regex against it.
you should use,
var myEmailRegEx = new RegExp("/\w+#\w+\.[a-z]|[A-Z]|\d|\.|-{2,}")
myEmailRegEx.test(document.getElementById("EmailAddress").value)
Suppose that email address is present in a form with id = "my_form". To prevent the default submission of that form, you would use
$("#my_form").preventDefault();
if the email turns out to be true, you could then submit the form.
if(myEmailRegEx.test(document.getElementById("EmailAddress").value)){
document.getElementById("mu_form").submit();
}
that should be it. I hope you have an idea where to plug in these code snippets :-)
Could just do:
<input type="email" />
and be done with it.
Try using an onchange event on the input field contain the email. For example:
<input type="text" name="Email" id="EmailAddress" size="50" onchange="validateEmail();" />
<br />
<input type="submit" value="Submit Email"/>
The above approach will call your validateEmail function whenever the value changes in that field.
While this doesn’t directly answer your question, it should be noted that your regex returns a lot of false negatives. For example, and email address with a . in the address, such as my personal email address, first.last#gmail.com
A good starting place is to start here
I will copy the "basic" email regex below for convenience.
^[A-Z0-9._%+-]+#[A-Z0-9.-]+\.[A-Z]{2,4}$
Related
in HTML, type="email" of input element can validate if an input string has a valid email format.
I would like to write a javascript program which will act differently when an input string to such an input element has or doesn't have a valid email format.
Can a javascript program read the validation result given by type="email" of input element? If not, why?
Or do I have to implement validation of email format in Javascript instead?
Thanks.
You can use the :invalid pseudoselector and querySelectorAll. In the following two email inputs - one with an invalid value set and one with a valid email. Css styling (using the :invalid pseudoselector to indicate which one is which. The console log will query all inputs that are invalid and log them.
The bigger issue may be the validation that is required to pass may be as simple as requiring a "#" symbol - so this is not a very stringent validation.
var test = document.querySelectorAll('input:invalid');
console.log(test);
input:invalid{background: red}
<input type="email" value="blah.com"/>
<input type="email" value="blah#blah.com"/>
It seem you can do something like this
<form id='form' action='post'>
<input id='email' type='email' required/>
<input type='submit' value='Submit'/>
</form>
<script>
console.log( document.getElementById('form').checkValidity() );
console.log( document.getElementById('email').checkValidity() );
</script>
For instance in this example;
<form>
<input type="email" name="email" id="useremail" placeholder="Email Address" required> <br>
<input type="tel" name="phone" id="userphone" placeholder="Phone Number" maxlength="10" required> <br>
<input type="submit" id="sidebarformsubmit" value="Submit">
</form>
Is it possible to somehow/somewhere be able to identify that the user has inputed something in EITHER the email or phone number field. So that on submit it doesn't show "this is required".
Reword: Can at least one of the form inputs be mandatory, both is allowed as is one or the other but not none. In the above example, the user needs to have at least one form of communication whether that be phone number or email. They can have both however, but not none.
If so, how would you go about this?
You can easily capture the change events from the inputs and set the required attribute accordingly.
Like this:
var email = document.getElementById('useremail'),
phone = document.getElementById('userphone');
function onchange(){
email[phone.value?'removeAttribute':'setAttribute']('required','required');
phone[email.value?'removeAttribute':'setAttribute']('required','required');
}
email.addEventListener('change',onchange);
phone.addEventListener('change',onchange);
jsfiddle
Is it possible to somehow/somewhere be able to identify that the user has inputed something in EITHER the email or phone number field. So that on submit it doesn't show "this is required".
1) No. If you use HTML5 required on a field then that field is required. There is no way to specify interdependence.
2) Yes. You can use client-side javascript validation, generally hooked to a form submit event to do as-complex-as-you-like validation. Prevent the submit by returning false from the event handler if you don't pass validation.
3) Yes. You can do validation that can be as complex as necessary on the server when you have received the submitted form, and return directly to the form if something is wrong.
3b) You Must do validation on the server, even if you have great client-side javascript validation, otherwise I will buy things from your site for one penny. You must not trust the client.
I want to make two text field as follows
<input id="email" class="email" value = "${user.email}" />
<input id="password" class="password" display="none" />
I'd like to change my email with current password. So I want to make password text field (its default display is none) to be activated, when I try to type in email text field to change email address.
To to this, I use javascript code. How can I make a code for this?
Should I use focus() or live() for this? Please let me know.
Thanks
try
$('#email').keyup(function() {
$('#password').show();
}
I have a form with two inputs:
<input type="text" name="keyword" value="Search" onfocus="wipe(this)"/>
<input type="text" name="city" value="City" onfocus="wipe(this)"/>
and my JavaScript which gets rid of the pre-set value in form field as soon as you click it with your mouse is:
function wipe(obj)
{
obj.value="";
}
My question is, say the user doesn't type anything in the city field, how do I make it so that when the form is submitted the value for that field is empty and not the word City?
placeholder is a good attribute which can solve your problem its a past time history when we are used to using value for showing for which this textbox we have
<input type="text" name="keyword" placeholder="Search" />
if you still want to use java script modify your code something like this
<input type="text" name="keyword" value="Search" onfocus="wipe(this,'Search')" onblur="wipe2(this,'Search')"/>
<input type="text" name="city" value="City" onfocus="wipe(this,'City')" onblur="wipe2(this,'City')"/>
script function for second approch
function wipe(obj, str)
{
if(obj.value!=str){
obj.value="";}
}
function wipe2(obj, str)
{if(obj.value==""){
obj.value=str;}
}
You are using the wrong technique here. you should be using placeholder which is supported by most major browsers with the regular exception of IE. So if this is not a concern for you, you should definitely be using that. Especially, if you have a label element for that field. Otherwise you'd need to be checking for that input value on submission and see if it equals the string city
Just Declare a variable hasChanged and set it true when wipe function is called.Then call a function say 'SubmitFunction()'on the onclick function of Submit button.
<input type="text" name="keyword" value="Search" id="Search" onfocus="wipe(this)"/>
<input type="text" name="city" value="City" id="City" onfocus="wipe(this)"/>
<input type="submit" name="submit" value="submit" onclick="SubmitFunction();"/>
var hasChanged=false;
function wipe(obj)
{
hasChanged=true;
obj.value="";
}
function SubmitFunction()
{
if(hasChanged==false)
{
$("#City").val('');
}
}
at the time of submit why not check for value='city'
if(obj.value!='city')
{
//your code here
}
or if you have no problem in using jquery use watermark plugin this will handle browser compatibility problem also
Jquery Watermark
try this:
if($('input[name="city"]').val() && $('input[name="city"]').val() != 'city') { yourform.submit(); }
See How to prepopulate input text fields with prompting text which disappears on typing (jQuery) for some solutions to this. If you're okay with using HTML5, the best solution is probably to use "placeholder" instead of "value".
You should add one more attribute(eg. default <input type="text" name="keyword" default="Search" value="Search" onfocus="wipe(this)"/>) with value same as value attribute.
in on submit compare each form fields
function onSubmit(){
for (var fields in form)
if(form[fields].value== form[fields].getAttribute("default")){
form[fields].value = "";
}
}
}
I have a usual login form consisting of two input fields, one for login, one for password. I am currently trying to add a control that will show entered password as plain text, so user can check it for typos.
The problem is that browsers (at least Firefox) do not allow dynamic changing of type attribute of input fields, so I cannot just change type="password" to type="text". Another problem is that browsers do not allow to get value of password field, so I can't create a new input type="text" and set its value to the password's one. I've seen several different approaches to this task, including this one, but they are working only if the password is typed and fail when browser autofills the password.
So, any suggestions to do this are welcome. I am using jQuery.
You can do something like this:
<input type="password" id="password">
<input type="checkbox" onchange="document.getElementById('password').type = this.checked ? 'text' : 'password'"> Show password
If I may, I don't think it's a great idea to show the password in text, for the following reasons:
It's not commonly done, so it will be confusing to the user
It means you are open to over-the-shoulder viewing of the password
I also think, if you just want to help users avoid typos, give them more chances before the password is disabled. I think the typical "3" that most sites implement is not really required, I'd suggest "10" attempts, or perhaps "5", if you wish to be really conservative, is quite acceptable. Just count it down for them, and let them resolve typos on their own.
Just my humble opinion.
I have never tried this myself but can't you just access the value property of the element?
if you have something like...
<input id="pw" name="pw" type="password" />
Then in JavaScript / jQuery...
var pass = document.getElementById('pw').value;
$('pw').val()
There is no any possibility to show autofilled password for security reasons. Anyone could see your password on your computer for this page if this is possible.
You have to deal with following for complete solution:
javascript is not allowed - then you should not display choose password checkbox
autocomplete is turned on - as I wrote, you're not able to show password filled this way. Eaighter switch off autocomplete or hide show password until user re-type password.
Autocomplete switch off by this jQuery
$('input').attr('autocomplete', 'off');
For adding checkbox on the fly you can use following jquery-showPassword plugin available at http://www.cuptech.eu/jquery-plugins/
$('.show-password').change(function() {
if ($("#form-fields_show-password").attr('checked')) {
var showValue = $('#form-fields_password').val();
var showPassword = $('<input type="text" size="50" required="required" name="form- fields[password]" id="form-fields_password" class="password required" value="'+showValue+'">');
$('#form-fields_password').replaceWith(showPassword);
} else {
var hideValue = $('#form-fields_password').val();
var hidePassword = $('<input type="password" size="50" required="required" name="form-fields[password]" id="form-fields_password" class="password required" value="'+hideValue+'">');
$('#form-fields_password').replaceWith(hidePassword);
}
});
Something like this will find the input area, and store the value in a variable called showValue. Then you can replace the element with type="password", with new html where type="text" and if the checkbox is unchecked the value will be dropped into password type field.
There is a problem with this method in that the password type value will be visible in the code, however to get round this you can always remove the value attribute from the password type and just force the user to re-type. If you can live with that in you application.
function change(){
id.type="password";
}
<input type="text" value="123456" id="change">
<button onclick="pass()">Change to pass</button>
<button onclick="text()">Change to text</button>
<script>function pass(){document.getElementById('change').type="password";} function text(){document.getElementById('change').type="text"; } </script>
Password: <input type="password" value="" id="myInput"><br><br>
<input type="checkbox" onclick="myFunction()">Show Password
<script>
function myFunction() {
var x = document.getElementById("myInput");
if (x.type === "password") {
x.type = "text";
} else {
x.type = "password";
}
}
</script>