Add suffix to form field - javascript

I have some (more than thousand) users that insist on logging in just with their names, but a system that insists on having the full e-mail address (name + #my-mail.com) provided. Which is a smart solution to add a suffix to a field without bothering the user?
The Form:
<form id="login_form" action="processing.php" method="post" class="form">
<fieldset>
<ul class="input_block">
<li>
<input type="text" name="email" id="email" value="" />
</li>
<li>
<input type="password" name="passwort" id="password" />
</li>
</ul>
</fieldset>
I played around with the key up function for the field, but it didn't help much.
<script>
$('#email').keyup(function(e){
if(this.value.length > 12){
this.value = this.value + '#my-mail.com';
if( this.value.indexOf('#my-mail.com') <= 0 ){
this.value = String.fromCharCode(e.which) + '#my-mail.com';
}
});
</script>
I consider a solution that manipulates the field just right before the submission much more "proper" (sadly I don't have access to the PHP file that is receiving the submission). So I tried as well with the submit function, this didn't work either.
<script>
$( "#login_form" ).submit(function( event ) {
("#email").value = ("#email").value + '#my-mail.com';
});
</script>
Anybody some advise on how to solve it using the submit function or another idea that seems to be better?

$('#email').change(function() {
var val = $(this).val();
if(val.indexOf('#my-mail.com') == -1)
$(this).val(val+'#my-mail.com');
});
http://jsfiddle.net/g4oLtfw7/
This will add the '#my-mail.com' suffix if it's not already part of the input value. If you want to allow other types of emails, but default to 'my-mail.com' otherwise, try this:
$('#email').change(function() {
var val = $(this).val();
if(val.indexOf('#') == -1)
$(this).val(val+'#my-mail.com');
});

Either:
$('#login_form').submit(function (e) {
var email = $('#email'),
user = email.val().split('#')[0],
domain = '#my-mail.com';
if (email.val().toLowerCase() !== (user + domain).toLowerCase()) {
email.val(user + domain);
}
});
or
$('#email').change(function (e) {
var email = $(this),
user = email.val().split('#')[0],
domain = '#my-mail.com';
if (email.val().toLowerCase() !== (user + domain).toLowerCase()) {
email.val(user + domain);
}
});
is how I would approach this (obligatory fiddle: http://jsfiddle.net/e84v7nat/).
This approach ensures that your user has a domain specified and that the domain is correct. If the username is case-sensitive, remove the calls to .toLowerCase.

Related

JavaScript HTML validation function only works when the form elements are all filled

I'm making sign in form with submit. What I want to do is to alert when there is blank in the form. But the function only works when all of the form are filled. Here's the HTML and JS code. The result is the same using onsubmit inside of the HTML or addEventListener("submit" function name)
HTML : It's basically a form for sign in / ordering.
<form id="registration" method="POST" onsubmit="return validate();" action="phplink">
<p> <label for="custName">Name : </label>
<input type="text" id="cname" name="cname" required="required" /> </p>
</form>
JS :
function validate(event) {
event.preventDefault();
var r = document.getElementById("registration");
var cname = r.cname.value;
var errMsg = "";
if (cname == "") {
errMsg += "Please enter your Name.\n";
}
if (errMsg.length != 0) {
alert(errMsg);
result = false;
}
return result;
}
The validation constrains, such as your required="required" are validated before your browser will trigger a submit event. If the validation fails (a value to a required field is not provided) it will not submit your form.
If you want to do the validation using JavaScript instead of the validation constraint attributes, you either need to remove the required="required" attribute (together with any other similar attributes) or you can add the novalidate attribute to your form to indicate that it should not perform this validation on submit.
If you use the latter, you can still use formElement.reportValidity() to see if all the elements satisfy their validation constraints.
If you add a required attribute to each field that shouldn’t be blank, it’ll prevent form submission with empty fields, like this...
<input type="text" name="username" required>
Hi you have several problem. on submit must pass event => onsubmit="return validate(event);" .
you must first defined result and thats your flag => var result = false .
if you want show alert then input dont need required attribute.
so this is your Fixed Code;
function validate(event) {
event.preventDefault();
var result = true;
var r = document.getElementById("registration");
var cname = r.cname.value;
var errMsg = "";
if (cname == "") {
errMsg += "Please enter your Name.\n";
}
if (errMsg.length != 0) {
alert(errMsg);
result = false;
}
return result;
}

Why is return false not keeping my form from submitting?

http://jsfiddle.net/1z9Lr5rv/1/
I am creating a contact form for my website. I thought it was working fine, but it always submits the form, wether or not there's an error, where return false should keep the form from submitting.
I'm sorry if this is really obvious and dumb, but I'm very new to this sort of thing . . .
The form works fine if you take it out of JS Fiddle (you should post the code here anyway). Here it is (with the redundant parts removed):
<div class="body">If you have any questions about me, my teaching or curriculum, etc., please don't hesitate to contact me here. Please fill out all the fields in this form..
<br>
<br>
<form name="contact-me" class="contact-me" onsubmit="return warnsub(this)"
method="POST"
action="https://secure.mailjol.net/allforms/u/3dcdda44.php" autocomplete="off">
First Name: <input type="text" name="fname">
Last Name: <input type="text" name="lname">
Email Address: <input type="text" name="email">
Message: <textarea name="message" id="message"></textarea>
<input type="submit" value="Send">
</form>
</div>
<script>
function warnsub(form) {
var error = [];
var fname = form.fname;
var lname = form.lname;
var email = form.email;
var message = form.message;
var atpos = email.value.indexOf("#");
var dotpos = email.value.lastIndexOf(".");
if (fname.value == "") {
error.push(fname);
}
if (lname.value == "") {
error.push(lname);
}
if (atpos < 1 || dotpos < atpos + 2 || dotpos + 2 >= email.length) {
error.push(email);
}
if (message.value == "") {
error.push(message);
}
if (error.length) {
for (i = 0; i < error.length; i++) {
// You want to clear this class if the user has another
// attempt and gets it right
error[i].className = 'error';
}
error[0].focus();
return false;
}
return true;
}
You need to handle the event object that is automatically passed into the submit handler and call preventDefault().
Example:
var myForm = document.forms["contact-me"];
myForm.onsubmit = function(e)
{
if(!warnsub())
{
e.preventDefault();
}
}
As #Pointy has commented: IE9 does not automatically pass the event object to the onsubmit delegate. Discussion of how to shiv this is outside the scope of this question.
But just a side note - its good to try and avoid function calls in inline html (e.g. <form onsubmit=//your function() /> calls. Your Google-Fu can teach you why.

Stop form from sending and execute a function

This is my form:
<form id="search_form" method="get" action="" name="search_f">
<input id="search_field" maxlength="100" name="query" type="text" value="" placeholder="cerca nel negozio">
<input id="search_button" type="submit" value="" onClick="submit_f()">
</form>
This is "submit_f()":
function submit_f(){
var v = document.search_f.query.value;
var v_arr = v.split("?");
alert(v_arr.join('\n'));
var v_arr = v_arr[0].split("/");
alert(v_arr.join('\n'));
if((v_arr[0] == "http:" || v_arr[0] == "https:") && v_arr[2] == "store.steampowered.com")
window.location.href = "/" + v_arr[3] + "/" + v_arr[4];
else
window.location.href = "/search/?query=" + v;
return false;
}
What I'm trying to do is to redirect the user to different pages based on what he enters:
- If he enters words he'll be redirected to "/search/?query=words".
- IF he enters an url (http://store.steampowered.com/app/202170/?asp=123) he'll be redirected (in this case) to "/app/202170".
But my code isn't working, any help?
You aren't returning anything from your event handler function:
onClick="submit_f()"
should be
onClick="return submit_f()"
You should give your form a
onsubmit="return false"
to avoid the default submitting behaviour. Also, your button could be type=button instead of type=submit, but that's not always enough (some browsers will still submit it), the sure way is onsubmit.
remove the onclick from your html
document.getElementById('search_button').onclick = function(){
var v = document.search_f.query.value;
var v_arr = v.split("?");
alert(v_arr.join('\n'));
var v_arr = v_arr[0].split("/");
alert(v_arr.join('\n'));
if((v_arr[0] == "http:" || v_arr[0] == "https:") && v_arr[2] == "store.steampowered.com")
window.location.href = "/" + v_arr[3] + "/" + v_arr[4];
else
window.location.href = "/search/?query=" + v;
return false;
}

JavaScript no response with validation

I am new to javascript and I am attempting to create a simple form validation. When I hit the submit button nothing happens. I have been looking at examples for a while and I cannot seem to figure out where I am going wrong. Any suggestions:
Right after this post I am going to break it all down and start smaller. But in the meantime I figured another set of eyes couldn't hurt and it is very possible I am doing something horribly wrong.
HTML:
<form name="form" action="index.html" onsubmit="return construct();" method="post">
<label>Your Name:<span class="req">*</span> </label>
<input type="text" name="name" /><br />
<label>Company Name:<span class="req">*</span> </label>
<input type="text" name="companyName" /><br />
<label>Phone Number:</label>
<input type="text" name="phone" /><br />
<label>Email Address:<span class="req">*</span></label>
<input type="text" name="email" /><br />
<label>Best Time to be Contacted:</label>
<input type="text" name="TimeForContact" /><br />
<label>Availability for Presenting:</label>
<input type="text" name="aval" /><br />
<label>Message:</label>
<textarea name="message" ROWS="3" COLS="30"></textarea>
<label>First Time Presenting for AGC?:<span class="req">*</span></label>
<input type="radio" name="firstTime" value="Yes" id="yes" /><span class="small">Yes</span>
<input type="radio" name="firstTime" value="No" id="no"/><span class="small">No</span><br /><br />
<input type="submit" name="submit" value="Sign-Up" />
</form>
JavaScript:
function construct() {
var name = document.forms["form"]["name"].value;
var companyName = document.forms["form"]["companyName"].value;
var email = document.forms["forms"]["email"].value;
var phone = document.forms["forms"]["phone"].value;
var TimeForC = document.forms["forms"]["TimeForContact"].value;
var availability = document.forms["forms"]["aval"].value;
if (validateExistence(name) == false || validateExistence(companyName) == false)
return false;
if (radioCheck == false)
return false;
if (phoneValidate(phone) == false)
return false;
if (checkValidForOthers(TimeForC) == false || checkValidForOthers(availability) == false)
return false;
if (emailCheck(email) == false)
return false;
}
function validateExistence(name) {
if (name == null || name == ' ')
alert("You must enter a " + name + " to submit! Thank you."); return false;
if (name.length > 40)
alert(name + " is too long for our form, please abbreviate."); return false;
}
function phoneValidate(phone) {
if (phone.length > 12 || phone == "" || !isNaN(phone))
alert("Please enter a valid phone number."); return false;
}
function checkValidForOthers(name) {
if (name.length > 40)
alert(name + " is too long for our form, please abbreviate."); return false;
}
function messageCheck(message) {
var currentLength = name.length;
var over = 0;
over = currentLength - 200;
if (name.length > 200)
alert(name + " is too long for our form, please abbreviate. You are " + over + " characters over allowed amount"); return false;
}
function radioCheck() {
if (document.getElementById("yes").checked == false || document.getElementById("no").checked == false)
return false;
}
function emailCheck(email) {
var atpos = email.indexOf("#");
var dotpos = email.lastIndexOf(".");
if (atpos < 1 || dotpos < atpos + 2 || dotpos + 2 >= email.length) {
alert("Not a valid e-mail address");
return false;
}
}
Am I calling my functions incorrectly? I honestly am not sure where I am going wrong.
I don't understand how to debug my code... I am using chrome and I am not receiving any errors in the console. Is there a way to set breakpoints to step through the javascript?
I realize i just threw a lot of code up there so thanks in advance for sifting through it.
Here is mistake:
Replace var email = document.forms["forms"]["email"].value;
by var email = document.forms["form"]["email"].value;
There are lot of places in your js :
var email = document.forms["forms"]["email"].value;
var phone = document.forms["forms"]["phone"].value;
var TimeForC = document.forms["forms"]["TimeForContact"].value;
var availability = document.forms["forms"]["aval"].value;
where you mistyped form as forms.
Is there a way to set breakpoints to step through the javascript?
Yes there is a way to set breakpoints:
Refer following links in order to know the method to set break-point in debugger console in Chrome:
LINK 1
LINK 2
The following should fix the immediate problem:
function construct(form) {
var
name = form["name"].value,
companyName = form["companyName"].value,
email = form["email"].value,
phone = form["phone"].value,
TimeForC = form["TimeForContact"].value,
availability = form["aval"].value
;
if (!validateExistence(name) || !validateExistence(companyName)) {
return false;
}
else if (!radioCheck) {
return false;
}
else if (phoneValidate(phone) == false) {
return false;
}
else if (!checkValidForOthers(TimeForC) || !checkValidForOthers(availability)) {
return false;
}
else if (emailCheck(email) == false) {
return false;
}
}
You had a typo in the form document.forms["forms"], where 'forms' doesn't exist. Instead of always traversing objects to get to your form, you can use this to pass the current element into your function.
<form action="index.html" onsubmit="return construct(this);" method="post">
If you're starting out it's also a good idea to make sure you set all your braces (i.e. curly brackets) as this will help you avoid getting confused with regards to alignment and brace matching.
Your first problem is the forms where you meant form. See here
But you have other problems with your validation code, for example:
if (name == null || name == ' ')
Here you are checking if name is null or name is a single space. I assume you wanted to check if the field is blank, but a completely empty string will evaluate as false in your condition, as will two spaces. What you probably want to do is something like this:
if (!name) {
// tell the user they need to enter a value
}
Conveniently (or sometimes not), Javascript interprets null, an empty string, or a string full of white space as false, so this should cover you.
You also have a whole host of other problems, see this:
http://jsfiddle.net/FCwYW/2/
Most of the problems have been pointed out by others.
You need to use braces {} when you have more than one line after an
if statement.
You need to return true when you pass you validation
tests or Javascript will interpret the lack of a return value as false.
Your radioCheck will only pass if both radio buttons are checked.
You where checking that your phone number was NOT NaN (i.e. it is a number) and returning false if it was.
I would suggest learning some new debug skills. There are ways to break down a problem like this that will quickly isolate your problem:
Commenting out code and enabling parts bit by bit
Using a debugger such as Firebug
Using console.log() or alert() calls
Reviewing your code line-by-line and thinking about what it is supposed to do
In your case, I would have first seen if name got a value with a console.log(name) statement, and then moved forward from there. You would immediately see that name does not get a value. This will lead to the discovery that you have a typo ("forms" instead of "form").
Some other errors in your code:
You are returning false outside of your if statement in validateExistence():
if (name == null || name == ' ')
alert("You must enter a " + name + " to submit! Thank you.");
return false;
In this case, you do not have brackets {} around your statement. It looks like return false is in the if(){}, but it is not. Every call to this code will return false. Not using brackets works with a single call, but I don't recommend it, because it leads to issues like this when you add additional code.
In the same code, you are using name as the field name when it is really the value of the field:
alert("You must enter a " + name + " to submit! Thank you."); return false;
You really want to pass the field name separately:
function validateExistence(name, field) {
if (name == null || name == ' ') {
alert("You must enter a " + field + " to submit! Thank you.");
return false;
} else if (name.length > 40)
alert(field + "value is too long for our form, please abbreviate.");
return false;
}
}
You are not calling radioCheck() because you are missing parentheses:
if (radioCheck == false)
In radioCheck(), you are using || instead of &&. Because at least 1 will always be unchecked by definition, you will always fail this check:
if (document.getElementById("yes").checked == false || document.getElementById("no").checked == false) return false;
And more...
My suggestion is to enable one check at a time, test it, and once it works as expected, move on to the next. Trying to debug all at once is very difficult.
replace var email = document.forms["forms"]["email"].value;
by
var email = document.forms["form"]["email"].value;
Try With Different Logic. You can use bellow code for check all four(4) condition for validation like not null, not blank, not undefined and not zero only use this code (!(!(variable))) in javascript and jquery.
function myFunction() {
var data; //The Values can be like as null,blank,undefined,zero you can test
if(!(!(data)))
{
alert("data "+data);
}
else
{
alert("data is "+data);
}
}

How to refresh the form value using JQuery

I have a html form. I want to take the input value (a url), extract a number from the url using regex ( '/[0-9]{5,}/') , and then refresh the form value with the number extracted and appended to another url. If I can't find a number - I just want an error to appear in the form box. All using Jquery to avoid page reload.
This is the existing form
<form id = "submit" method="post">
<label for="link_website_url">Create a short url</label>
<input id="link_website_url" name="link" size="30" type="text" />
<input class="go" name="commit" type="submit" value="Go!" /></form>
$('#submit').submit(function(){
var url = $('#link_website_url').val(); //http://example.com/12345
var num = yourNumExtractorFunction(url); //returns -1 if there is no number extracted
if(num > -1){
$('#link_website_url').val('http://otherdomain.com/' + num); //http://otherdomain.com/12345
}else{
$('#link_website_url').after('<span id="error_link_web_url" class="error">Incorrect format! Please try again.</span>');
return false; //error, so cancel this submit
}
});
If you perform additional validation, cancel the submit even if an individual check passes, clear error messages per check that validates (e.g. $('#error_link_web_url').remove();) and submit after all checks pass:
var checkFailed = false;
$('#submit').submit(function(){
var url = $('#link_website_url').val(); //http://example.com/12345
var num = yourNumExtractorFunction(url); //returns -1 if there is no number extracted
if(num > -1){
$('#link_website_url').val('http://otherdomain.com/' + num); //http://otherdomain.com/12345
$('#error_link_web_url').remove();
}else{
$('#link_website_url').after('<span id="error_link_web_url" class="error">Incorrect format! Please try again.</span>');
checkFailed = true;
}
/*Other checks...*/
if(checkFailed){
return false; //cancel submit
}
});
$('#submit').submit(function(){
var url = $('#link_website_url').value();
var val = <do your processing here>;
$('#link_website_url').value(val);
return false;
});

Categories

Resources